import { Collection } from "https://deno.land/x/mongo@v0.31.2/mod.ts"; import HttpError from "../server/HttpError.ts"; import User from "../models/User.ts"; import { rest } from "../server/Router.ts"; import { body, schema } from "../server/decorators.ts"; import AppRouter from "./AppRouter.ts"; import * as bcrypt from "https://deno.land/x/bcrypt@v0.4.1/mod.ts"; interface SignupRequest { username: string; password: string; } export default class UserRouter extends AppRouter { @rest('GET', '/') async get(@schema('string') username: string) { const res = await this.users.findOne({ username }); if (res === undefined) throw new HttpError('User not found.'); return { username: res.username }; } @rest('POST', '/signup') async signup( @schema({ username: 'string', password: 'string', }) @body() body: SignupRequest ) { if (await this.users.countDocuments({ username: body.username }) > 0) { throw new HttpError('User with the same username already exists.'); } const password = await bcrypt.hash(body.password, this.salt); await this.users.insertOne({ username: body.username, password: password, }); return {}; } public constructor(private salt: string, private users: Collection) { super(); users.createIndexes({ indexes: [ { key: { username: 1 }, name: 'Username Index' } ] }); } }