70 lines
1.8 KiB
TypeScript
70 lines
1.8 KiB
TypeScript
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<User>;
|
|
|
|
constructor(db: Db) {
|
|
this.collection = db.collection<User>('users');
|
|
}
|
|
|
|
public async login(tracker: string, data: LoginUserBody): Promise<User> {
|
|
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<User> {
|
|
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<User> {
|
|
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;
|