1 import {DuplicateContentError, ERROR_CODE, NotFoundError} from '../errors';
2 import { v4 as uuid } from 'uuid';
3 import {Repository} from './base';
4 import { Session, SessionRepository } from './session';
5 import bcrypt from 'bcrypt';
7 export type Account = {
13 export class AccountRepository extends Repository<Account> {
14 session: SessionRepository;
17 this.session = new SessionRepository();
20 async login(username: string, password: string): Promise<{account: Account, session: Session}> {
21 const account = await this.FindOne({
26 throw new NotFoundError('User not found', ERROR_CODE.USER_NOT_FOUND);
29 if(!await bcrypt.compare(password, account.password)) {
30 throw new NotFoundError('User not found', ERROR_CODE.USER_PASSWORD_INCORRECT);
33 const session = await this.session.create(account.id);
41 async validate(accountId: string, token: string): Promise<Account> {
43 const session = await this.session.validate(accountId, token);
44 const account = await this.FindOne({id: session.account_id});
47 throw new NotFoundError('User not found', ERROR_CODE.USER_NOT_FOUND);
52 throw new NotFoundError('User not found', ERROR_CODE.INVALID_USER_TOKEN);
56 async create(username: string, password: string) {
57 const user = await this.Insert({
60 password: await this.hash(password)
64 throw new DuplicateContentError('Username in user', ERROR_CODE.USER_ALREADY_EXISTS);
70 async hash(password: string): Promise<string> {
71 return bcrypt.hash(password, 10);