auth init
This commit is contained in:
1 parent
faa2e70e08
commit
413aeedadf
29 files changed
+2854
-649
No files matched your search
@@ -0,0 +1,7 @@
|
||||
# Environment variables declared in this file are automatically made available to Prisma.
|
||||
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
|
||||
|
||||
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
|
||||
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
|
||||
|
||||
DATABASE_URL="postgresql://mcrates:digdeep@0.0.0.0:45432/mcrates?schema=public"
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extension": ["ts"],
|
||||
"spec": "src/**/*.test.ts",
|
||||
"require": "ts-node/register",
|
||||
|
||||
"watch-files": "**/*.ts",
|
||||
"watch-ignore": ["db"]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
listings
|
||||
doc
|
||||
release
|
||||
|
||||
wants
|
||||
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
// global type aliases and whatnot
|
||||
|
||||
type UUID = string;
|
||||
type Email = string;
|
||||
|
||||
type DiscogsName = string;
|
||||
type DiscogsListing = number;
|
||||
type DiscogsRelease = number;
|
||||
type DiscogsSeller = number;
|
||||
|
||||
type BundleCandidate = {
|
||||
seller: DiscogsSeller,
|
||||
count: number,
|
||||
listings: DiscogsListing[],
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import createServices from './src/services';
|
||||
import createLog from './src/log';
|
||||
|
||||
async function start() {
|
||||
const log = createLog();
|
||||
|
||||
process.on('SIGTERM', () => {
|
||||
log.debug('SIGTERM received, exiting');
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
const {
|
||||
prisma,
|
||||
pg,
|
||||
discogs,
|
||||
api,
|
||||
} = createServices(log);
|
||||
|
||||
await api.listen();
|
||||
}
|
||||
|
||||
start();
|
||||
Generated
+5799
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "mates-crates",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "mocha",
|
||||
"test:watch": "mocha --watch",
|
||||
"migrate": "knex migrate:latest",
|
||||
"migrate:make": "prisma migrate dev --name",
|
||||
"start": "ts-node-dev --respawn --transpile-only index.ts | bunyan -o short"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.0",
|
||||
"@types/bluebird": "^3.5.36",
|
||||
"@types/koa": "^2.13.5",
|
||||
"@types/lodash": "^4.14.182",
|
||||
"@types/mocha": "^9.1.1",
|
||||
"axios": "^0.27.2",
|
||||
"mocha": "^10.0.0",
|
||||
"node-dev": "^7.4.3",
|
||||
"prisma": "^4.1.0",
|
||||
"ts-node-dev": "^2.0.0",
|
||||
"typescript": "^4.7.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@koa/cors": "^3.3.0",
|
||||
"@koa/router": "^12.0.0",
|
||||
"@prisma/client": "^4.1.0",
|
||||
"bcrypt": "^5.0.1",
|
||||
"bluebird": "^3.7.2",
|
||||
"bunyan": "^1.8.15",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"koa": "^2.13.4",
|
||||
"koa-body": "^5.0.0",
|
||||
"koa-passport": "^5.0.0",
|
||||
"koa-session": "^6.2.0",
|
||||
"lodash": "^4.17.21",
|
||||
"passport-local": "^1.0.0"
|
||||
},
|
||||
"overrides": {
|
||||
"koa-passport": {
|
||||
"passport": "^0.5"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
previewFeatures = ["interactiveTransactions"]
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model Listing {
|
||||
id Int @id
|
||||
seller Int
|
||||
data Json
|
||||
|
||||
wantId String @db.Uuid
|
||||
want Want @relation(fields: [wantId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([seller])
|
||||
@@map("listings")
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||
email String @unique
|
||||
password String
|
||||
discogs String? @unique
|
||||
data Json?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
wants Want[]
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Want {
|
||||
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||
release Int?
|
||||
data Json
|
||||
|
||||
userId String @db.Uuid
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
listings Listing[]
|
||||
|
||||
@@unique([userId, release])
|
||||
@@index([release])
|
||||
|
||||
@@map("wants")
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from 'assert/strict';
|
||||
import axios from 'axios';
|
||||
|
||||
import createServices from './services';
|
||||
import createLog from './log';
|
||||
|
||||
const log = createLog();
|
||||
log.level('error');
|
||||
const services = createServices(log);
|
||||
|
||||
const HOST = 'http://localhost:41337';
|
||||
|
||||
before(function setup() {
|
||||
console.log('setup')
|
||||
services.api.listen();
|
||||
});
|
||||
|
||||
after(function teardown(done) {
|
||||
services.api.server.close(done)
|
||||
});
|
||||
|
||||
describe('api', function apiTests() {
|
||||
it('listens', async function listenTest() {
|
||||
const res = await axios.get(`${HOST}/health`);
|
||||
assert.equal(res.status, 200);
|
||||
});
|
||||
|
||||
it('register', async function register() {
|
||||
const body = {
|
||||
email: `test+${Date.now()}@user.com`,
|
||||
password: 'woaaah theres no limit',
|
||||
};
|
||||
const { data } = await axios.post(`${HOST}/auth/register`, body);
|
||||
assert.equal(data.email, body.email);
|
||||
});
|
||||
|
||||
it('login', async function login() {
|
||||
const body = {
|
||||
email: `test+${Date.now()}@user.com`,
|
||||
password: 'woaaah theres no limit',
|
||||
};
|
||||
await axios.post(`${HOST}/auth/register`, body);
|
||||
const res = await axios.post(`${HOST}/auth/login`, body);
|
||||
assert(res.headers['set-cookie']);
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
import http from 'http';
|
||||
|
||||
import koa from 'koa';
|
||||
import bodyParser from 'koa-body';
|
||||
import session from 'koa-session';
|
||||
import koaRouter from '@koa/router'
|
||||
import cors from '@koa/cors';
|
||||
|
||||
import { groupBy } from 'lodash';
|
||||
import Bluebird from 'bluebird';
|
||||
|
||||
import type Log from 'bunyan';
|
||||
import type { Listing, User, Want, Prisma } from '@prisma/client';
|
||||
|
||||
import { Pg } from './pg';
|
||||
import routerAuth from './routers/router.auth';
|
||||
|
||||
export default function createApi(log: Log, pg: Pg, discogs) {
|
||||
const PORT = 41337;
|
||||
const SECRET = 'ohja4Eif9eidah3aj5ta2haa4iemooth';
|
||||
|
||||
const app = new koa();
|
||||
const server = http.createServer(app.callback());
|
||||
|
||||
// app.use(async (ctx, next) => {
|
||||
// try {
|
||||
// await next();
|
||||
// } catch (err) {
|
||||
// log.error(err);
|
||||
// ctx.status = err.statusCode || err.status || 500;
|
||||
// ctx.body = {
|
||||
// message: err.message
|
||||
// };
|
||||
// }
|
||||
// });
|
||||
|
||||
const router = koaRouter();
|
||||
|
||||
interface ListingData extends Listing {
|
||||
data: any,
|
||||
want: { user: User },
|
||||
};
|
||||
|
||||
async function getBundles() {
|
||||
const bundles = await pg.bundleCandidates();
|
||||
|
||||
return bundles.map((b: ListingData[]) => {
|
||||
const total = b.reduce((acc, l) => acc + l.data.original_price.value, 0);
|
||||
|
||||
const items = b.map(l => ({
|
||||
id: l.data.id,
|
||||
description: l.data.release.description,
|
||||
price: l.data.original_price.value,
|
||||
currency: l.data.original_price.curr_abbr,
|
||||
condition: l.data.condition,
|
||||
uri: l.data.uri,
|
||||
user: l.want.user,
|
||||
}));
|
||||
|
||||
const shipping = b[0]?.data.seller.shipping;
|
||||
|
||||
const bundle = {
|
||||
username: b[0]?.data.seller.username,
|
||||
seller: b[0]?.data.seller.id,
|
||||
shipsFrom: b[0]?.data.ships_from,
|
||||
total,
|
||||
currency: b[0]?.data.original_price.curr_abbr,
|
||||
shipping: '...',
|
||||
items,
|
||||
mentionsAustralia: shipping.toLowerCase().includes('australia'),
|
||||
mentionsWorldwide: shipping.toLowerCase().includes('world'),
|
||||
}
|
||||
|
||||
return bundle;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async function populateUserListings(user: User) {
|
||||
const wants = await discogs.wantlist(user);
|
||||
|
||||
// const latest = await discogs.wantlistLatest(user);
|
||||
// if (wants.length !== latest.length)
|
||||
|
||||
log.debug({ username: user.discogs, wantCount: wants.length });
|
||||
|
||||
return Bluebird.mapSeries<Want, Listing[]>(wants, async want => {
|
||||
const listings = await discogs.listings(want);
|
||||
const populated = listings.filter(l => l);
|
||||
log.debug({ id: want.id, release: want.release, populated: populated.length, total: listings.length });
|
||||
return populated;
|
||||
});
|
||||
}
|
||||
|
||||
function listen() {
|
||||
return new Promise((resolve, reject) => {
|
||||
app.on('error', err => {
|
||||
reject(err);
|
||||
})
|
||||
|
||||
server.listen(PORT, () => {
|
||||
log.info('listening', { PORT });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
app.use(cors({ origin: false, credentials: true }));
|
||||
app.use(bodyParser())
|
||||
|
||||
app.keys = [SECRET];
|
||||
app.use(session(app));
|
||||
|
||||
const { authRouter, passport } = routerAuth(log, pg);
|
||||
app.use(passport.initialize());
|
||||
app.use(passport.session())
|
||||
app.use(authRouter.routes());
|
||||
|
||||
router.get('/health', async function health(ctx) {
|
||||
ctx.status = 200;
|
||||
});
|
||||
|
||||
async function requireAuth(ctx, next) {
|
||||
log.warn(ctx.isAuthenticated());
|
||||
await next();
|
||||
}
|
||||
|
||||
router.get('/bundles', requireAuth, async (ctx, next) => {
|
||||
const bundles = await getBundles();
|
||||
ctx.response.body = bundles;
|
||||
})
|
||||
|
||||
router.get('/user/:id/offers', async function userOffersGet(ctx, next) {
|
||||
const { id } = ctx.request.params;
|
||||
const user = await pg.userFindId(id);
|
||||
|
||||
// if (!user) return ctx.response.status = 404;
|
||||
|
||||
const bundles = (await getBundles())
|
||||
.map(b => {
|
||||
b.items = b.items.filter(i => i.user.id === user.id)
|
||||
return b;
|
||||
})
|
||||
.filter(b => b.items.length);
|
||||
|
||||
ctx.response.body = bundles;
|
||||
});
|
||||
|
||||
router.post('/user/populate', async function usersPopulate(ctx, next) {
|
||||
const { userId } = ctx.request.body;
|
||||
const user = await pg.userFindId(userId);
|
||||
const listings = await populateUserListings(user);
|
||||
ctx.response.body = listings;
|
||||
});
|
||||
|
||||
router.post('/want', async function wantPost(ctx, next) {
|
||||
const { userId, releaseId } = ctx.request.body;
|
||||
const user = await pg.userFindId(userId);
|
||||
const release = await discogs.release(releaseId);
|
||||
const want = await pg.wantUpsert(release, user);
|
||||
ctx.response.body = want;
|
||||
});
|
||||
|
||||
router.post('/want/search', async function wantPost(ctx, next) {
|
||||
const { artist, title } = ctx.request.body;
|
||||
const results = await discogs.search(artist, title);
|
||||
ctx.response.body = results;
|
||||
});
|
||||
|
||||
app.use(router.routes());
|
||||
|
||||
return {
|
||||
app,
|
||||
server,
|
||||
listen,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { KoaPassport } from 'koa-passport';
|
||||
import { Strategy as LocalStrategy } from 'passport-local';
|
||||
|
||||
export default function authService(pg) {
|
||||
const passport = new KoaPassport();
|
||||
|
||||
passport.serializeUser((user, done) => done(null, user.id));
|
||||
passport.deserializeUser((id, done) => {
|
||||
pg.userFindId(id)
|
||||
.then(u => done(null, u))
|
||||
.catch(e => done(e, null));
|
||||
})
|
||||
|
||||
passport.use(new LocalStrategy(
|
||||
{ usernameField: 'email '},
|
||||
function localStrategy(email, password, done) {
|
||||
pg.userFindEmail(email)
|
||||
.then(user => {
|
||||
if (!user) return done(null, false);
|
||||
// if (!user.verifyPassword(password)) return done(null, false);
|
||||
return done(null, user);
|
||||
})
|
||||
.catch(e => done(e, null));
|
||||
}
|
||||
));
|
||||
|
||||
return passport;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import fs from 'fs/promises';
|
||||
|
||||
import axios from 'axios';
|
||||
import cheerio from 'cheerio';
|
||||
import Bluebird from 'bluebird';
|
||||
|
||||
import type Log from 'bunyan';
|
||||
import type { PrismaClient, Want, User, Listing } from '@prisma/client';
|
||||
|
||||
import { logAxiosError } from './utils';
|
||||
import { Pg } from './pg';
|
||||
|
||||
export default function discogs(log: Log, pg: Pg) {
|
||||
const TOKEN = 'Discogs token=wRTXuYZGOPsIQgKRGKCAkUkidGtvpSfQgPWkYIpD';
|
||||
const apiBase = 'https://api.discogs.com'
|
||||
const discogsBase = 'https://www.discogs.com'
|
||||
|
||||
const api = axios.create({
|
||||
headers: {
|
||||
'Authorization': TOKEN,
|
||||
// discogs only returns the first page without a desktop u/a
|
||||
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0',
|
||||
},
|
||||
});
|
||||
|
||||
async function handleApiError(e) {
|
||||
logAxiosError(e);
|
||||
if (e.response.status === 429) {
|
||||
throw new Error('rate limited');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// async function user(discogs: string) {
|
||||
// const user = await pg.userFindName(discogs);
|
||||
// if (user) return user;
|
||||
// log.debug('fetching user', discogs);
|
||||
// const { data } = await api.get(`${apiBase}/users/${discogs}`);
|
||||
// return pg.userUpsert(data.username, data.username, data);
|
||||
// }
|
||||
|
||||
async function wantlist(user: User): Promise<Want[]> {
|
||||
const stored = await pg.userWants(user);
|
||||
if (stored.length) return stored;
|
||||
|
||||
if (!user.discogs) {
|
||||
log.error(user, 'attempted to fetch wantlist of non discogs user');
|
||||
throw new Error('User is not associated with a discogs account');
|
||||
}
|
||||
|
||||
return wantlistLatest(user);
|
||||
}
|
||||
|
||||
async function wantlistLatest(user: User): Promise<Want[]> {
|
||||
const { username } = user.data as { username: string };
|
||||
const { data: { wants, pagination }} = await api.get(`${apiBase}/users/${username}/wants`);
|
||||
return Bluebird.mapSeries(wants, async r => pg.wantUpsert(r, user));
|
||||
}
|
||||
|
||||
async function release(id: DiscogsRelease): Promise<any> {
|
||||
const { data } = await api.get(`${apiBase}/releases/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
async function search(artist: string, title: string) {
|
||||
const url = new URL(`${apiBase}/database/search`);
|
||||
url.searchParams.append('artist', artist);
|
||||
url.searchParams.append('title', title);
|
||||
url.searchParams.append('type', 'release');
|
||||
url.searchParams.append('format', 'vinyl');
|
||||
const { data: { results } } = await api.get(url.href);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function inventory(user: string) {
|
||||
const res = await api.get(`${apiBase}/users/${user}/inventory`);
|
||||
return res.data.listings;
|
||||
}
|
||||
|
||||
async function listings(want: Want) {
|
||||
const res = await api.get(`https://www.discogs.com/sell/release/${want.release}?limit=250`);
|
||||
const $ = cheerio.load(res.data);
|
||||
const ids = $('.item_description_title[href]')
|
||||
.map(function getListingId() {
|
||||
const id = Number.parseInt(this.attribs.href.replace('/sell/item/', ''), 10);
|
||||
return id;
|
||||
})
|
||||
.get();
|
||||
|
||||
const unlisted = await pg.listingRmUnlisted(want, ids);
|
||||
if (unlisted) log.info({ wantId: want.id, unlisted: unlisted }, 'missing listings removed');
|
||||
return Bluebird.mapSeries(ids, async id => listing(id, want));
|
||||
}
|
||||
|
||||
async function listing(id, want) {
|
||||
const listing = await pg.listingFind(id);
|
||||
if (listing) return listing;
|
||||
|
||||
try {
|
||||
log.debug('fetching listing', id);
|
||||
const res = await api.get(`${apiBase}/marketplace/listings/${id}`);
|
||||
return pg.listingUpsert(res.data, want);
|
||||
} catch (e) {
|
||||
return handleApiError(e);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
// user,
|
||||
wantlist,
|
||||
wantlistLatest,
|
||||
inventory,
|
||||
listings,
|
||||
listing,
|
||||
release,
|
||||
search,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import bunyan from 'bunyan';
|
||||
|
||||
export default function createLog() {
|
||||
const log = bunyan.createLogger({
|
||||
name: 'mcrates',
|
||||
stream: process.stdout
|
||||
});
|
||||
|
||||
return log;
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import bcrypt from 'bcrypt';
|
||||
import type Log from 'bunyan';
|
||||
import type { PrismaClient, Want, User, Listing, Prisma } from '@prisma/client';
|
||||
import * as Bluebird from 'bluebird';
|
||||
|
||||
export interface UserCreateParams {
|
||||
discogs: DiscogsName | null,
|
||||
email: string,
|
||||
password: string,
|
||||
data: any,
|
||||
}
|
||||
|
||||
export interface Pg {
|
||||
userFindId: (id: UUID) => Promise<User>,
|
||||
userFindEmail: (email: Email) => Promise<User>,
|
||||
userCreate: (params: UserCreateParams) => Promise<User>,
|
||||
userWants: (user: User) => Promise<Want[]>,
|
||||
|
||||
wantUpsert: (want: Want, user: User) => Promise<Want>,
|
||||
listingUpsert: (listing: Listing, want: Want) => Promise<Listing>,
|
||||
listingFind: (id: DiscogsListing) => Promise<Listing>,
|
||||
listingRmUnlisted: (want: Want, ids: DiscogsListing[]) => Promise<number>,
|
||||
|
||||
bundleCandidates: () => Promise<Listing[][]>,
|
||||
}
|
||||
|
||||
export default function createPg(log: Log, prisma: PrismaClient): Pg {
|
||||
async function userFindId(id: UUID) {
|
||||
return prisma.user.findUnique({ where: { id }});
|
||||
}
|
||||
|
||||
async function userFindEmail(email: Email) {
|
||||
return prisma.user.findUnique({ where: { email }});
|
||||
}
|
||||
|
||||
async function userWants(user: User) {
|
||||
return prisma.want.findMany({ where: { userId: user.id }});
|
||||
}
|
||||
|
||||
async function userCreate(params: UserCreateParams) {
|
||||
const hashRounds = 10;
|
||||
const password = await bcrypt.hash(params.password, hashRounds);
|
||||
|
||||
const data = {
|
||||
discogs: params.discogs,
|
||||
email: params.email,
|
||||
data: params.data,
|
||||
password,
|
||||
};
|
||||
|
||||
return prisma.user.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
async function wantUpsert(dcWant, user) {
|
||||
const values: { userId: UUID, release: DiscogsListing, data: any } = {
|
||||
data: dcWant,
|
||||
release: dcWant.id,
|
||||
userId: user.id,
|
||||
};
|
||||
|
||||
return prisma.want.upsert({
|
||||
// get these from the generated types
|
||||
// ./node_modules/.prisma/client/index.d.ts
|
||||
where: { userId_release: {
|
||||
userId: values.userId,
|
||||
release: values.release || null,
|
||||
}},
|
||||
update: values,
|
||||
create: values,
|
||||
});
|
||||
}
|
||||
|
||||
async function listingRmUnlisted(want: Want, ids: DiscogsListing[]) {
|
||||
const { count } = await prisma.listing.deleteMany({
|
||||
where: {
|
||||
wantId: want.id,
|
||||
id: {
|
||||
notIn: ids,
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
async function listingUpsert(listing, want) {
|
||||
const values = {
|
||||
id: listing.id,
|
||||
wantId: want.id,
|
||||
seller: listing.seller.id,
|
||||
data: listing,
|
||||
};
|
||||
|
||||
return prisma.listing.upsert({
|
||||
where: {
|
||||
id: listing.id
|
||||
},
|
||||
update: values,
|
||||
create: values,
|
||||
});
|
||||
}
|
||||
|
||||
async function listingFind(id: DiscogsListing) {
|
||||
return prisma.listing.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
want: {
|
||||
include: { user: true },
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function bundleCandidates(): Promise<Listing[][]> {
|
||||
const candidates = await prisma.$queryRaw`
|
||||
select
|
||||
seller, count(distinct("wantId")), array_agg(id) as listings
|
||||
from
|
||||
listings
|
||||
group by
|
||||
seller
|
||||
order by
|
||||
count desc
|
||||
limit 5;
|
||||
` as BundleCandidate[];
|
||||
|
||||
return Promise.all(candidates.map(async c => prisma.listing.findMany({
|
||||
where: {
|
||||
id: { in: c.listings }
|
||||
},
|
||||
include: {
|
||||
want: {
|
||||
include: { user: true },
|
||||
}
|
||||
},
|
||||
distinct: ['wantId'],
|
||||
})));
|
||||
}
|
||||
|
||||
return {
|
||||
userFindId,
|
||||
userFindEmail,
|
||||
userCreate,
|
||||
userWants,
|
||||
|
||||
wantUpsert,
|
||||
listingUpsert,
|
||||
listingFind,
|
||||
listingRmUnlisted,
|
||||
|
||||
bundleCandidates,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import bcrypt from 'bcrypt';
|
||||
import { KoaPassport } from 'koa-passport';
|
||||
import { Strategy as LocalStrategy } from 'passport-local';
|
||||
import Router from '@koa/router'
|
||||
|
||||
import type { Pg } from './../pg';
|
||||
|
||||
export default function authRouter(log, pg: Pg) {
|
||||
const passport = new KoaPassport();
|
||||
|
||||
async function verifyPassword(user, password) {
|
||||
const match = await bcrypt.compare(password, user.password);
|
||||
return match;
|
||||
}
|
||||
|
||||
passport.use(new LocalStrategy(
|
||||
{ usernameField: 'email' },
|
||||
function localStrategy(email, password, done) {
|
||||
pg.userFindEmail(email)
|
||||
.then(user => {
|
||||
if (!user) return done(null, false);
|
||||
if (!verifyPassword(user, password)) return done(null, false);
|
||||
return done(null, user);
|
||||
})
|
||||
.catch(e => done(e, null));
|
||||
}
|
||||
));
|
||||
|
||||
passport.serializeUser((user, done) => done(null, user.id));
|
||||
passport.deserializeUser((id, done) => {
|
||||
pg.userFindId(id)
|
||||
.then(u => done(null, u))
|
||||
.catch(e => done(e, null));
|
||||
})
|
||||
|
||||
const authRouter = new Router({ prefix: '/auth' });
|
||||
|
||||
authRouter.post('/login', async (ctx, next) => {
|
||||
await passport.authenticate('local', (err, user, info, status) => {
|
||||
if (user) {
|
||||
ctx.login(user);
|
||||
ctx.status = 200;
|
||||
ctx.body = { status: 'success' };
|
||||
} else {
|
||||
ctx.status = 400;
|
||||
ctx.body = { status: 'error' };
|
||||
}
|
||||
})(ctx, next);
|
||||
});
|
||||
|
||||
authRouter.post('/register', async (ctx, next) => {
|
||||
const { discogs, email, password } = ctx.request.body;
|
||||
// fetch discogs data if they have it
|
||||
const params = { discogs, email, password, data: {} };
|
||||
const user = await pg.userCreate(params)
|
||||
ctx.response.body = user;
|
||||
});
|
||||
|
||||
return { authRouter, passport };
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
import discogsService from './discogs';
|
||||
import pgService from './pg';
|
||||
import { logAxiosError } from './utils';
|
||||
import createLog from './log';
|
||||
import createApi from './api';
|
||||
|
||||
export default function createServices(log) {
|
||||
const prisma = new PrismaClient();
|
||||
const pg = pgService(log, prisma);
|
||||
const discogs = discogsService(log, pg);
|
||||
const api = createApi(log, pg, discogs);
|
||||
|
||||
return {
|
||||
prisma,
|
||||
pg,
|
||||
discogs,
|
||||
api,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export function logAxiosError(e) {
|
||||
console.warn({
|
||||
status: e.response.status,
|
||||
statusText: e.response.statusText,
|
||||
url: e.config.url,
|
||||
data: e.response.data,
|
||||
rateLimiting: {
|
||||
limit: e.response.headers['x-discogs-ratelimit'],
|
||||
remaining: e.response.headers['x-discogs-ratelimit-remaining'],
|
||||
used: e.response.headers['x-discogs-ratelimit-used'],
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es2020", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "commonjs", /* Specify what module code is generated. */
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
"types": [
|
||||
"./index.d.ts",
|
||||
"mocha"
|
||||
], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": false, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
},
|
||||
|
||||
"ts-node": {
|
||||
// strict mode gtfo
|
||||
"transpileOnly": true,
|
||||
},
|
||||
}
|
||||
Reference in new issue
Block a user