import { Collection, Db } from 'mongodb'; import { LoginUserBody, UserInfo } from '@core'; import { User, UserWithPassword } from '../../entities/user'; import log from '../../functions/logger'; import { generateHash } from '../../functions/password'; class UserModel { private collection: Collection; constructor(db: Db) { this.collection = db.collection('users'); } public async login(tracker: string, data: LoginUserBody): Promise { const checkUser = await this.collection.findOne({ username: data.username, }); if (!checkUser) { log(tracker, 'User Not Found'); throw new Error(); } const userDocument = await this.collection.findOne({ uuid: checkUser.uuid, password: generateHash(checkUser.uuid, data.password), }); if (!userDocument) { log(tracker, 'Wrong Password'); throw new Error(); } const user = new User(userDocument); log(tracker, 'LOG IN', user); return new User(user); } public async create( tracker: string, userInfo: UserWithPassword, ): Promise { const checkUser = await this.collection.findOne({ username: userInfo.username, }); if (checkUser) { log(tracker, 'User Already Exists'); throw new Error(); } await this.collection.insertOne(userInfo); const user = await this.read(tracker, userInfo.uuid); log(tracker, 'CREATE USER', user); return user; } public async read(tracker: string, uuid: string): Promise { const userDocument = await this.collection.findOne({ uuid }); if (!userDocument) { log(tracker, 'User Not Found'); throw new Error(); } const user = new User(userDocument); log(tracker, 'READ USER', user); return user; } } export default UserModel;