better errors + better tools

This commit is contained in:
2022-10-30 19:35:35 +01:00
parent 46a7e07b86
commit 82d356ef5e
7 changed files with 93 additions and 53 deletions

View File

@ -1,5 +1,5 @@
import { Collection, Db } from 'mongodb';
import { LoginUserBody } from '../../../../core/src/user';
import { LoginUserBody, UserInfo } from '@core';
import { User, UserWithPassword } from '../../entities/user';
import log from '../../functions/logger';
import { generateHash } from '../../functions/password';
@ -11,42 +11,58 @@ class UserModel {
this.collection = db.collection<User>('users');
}
public async login(tracker: string, data: LoginUserBody) {
public async login(tracker: string, data: LoginUserBody): Promise<User> {
const checkUser = await this.collection.findOne({
username: data.username,
});
if (checkUser === null) {
if (!checkUser) {
log(tracker, 'User Not Found');
return null;
throw new Error();
}
const user = await this.collection.findOne({
const userDocument = await this.collection.findOne({
uuid: checkUser.uuid,
password: generateHash(checkUser.uuid, data.password),
});
if (user === null) {
if (!userDocument) {
log(tracker, 'Wrong Password');
return null;
throw new Error();
}
const user = new User(userDocument);
log(tracker, 'LOG IN', user);
return new User(user);
}
public async create(tracker: string, user: UserWithPassword) {
await this.collection.insertOne(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 this.read(tracker, user.uuid);
return user;
}
public async read(tracker: string, uuid: string) {
const user = await this.collection.findOne({ uuid });
if (user === null) {
public async read(tracker: string, uuid: string): Promise<User> {
const userDocument = await this.collection.findOne({ uuid });
if (!userDocument) {
log(tracker, 'User Not Found');
return null;
throw new Error();
}
const user = new User(userDocument);
log(tracker, 'READ USER', user);
return new User(user);
return user;
}
}