summary refs log tree commit diff
path: root/src/db/dbAccess/user.js
blob: 6301cb5292d367c854c6151a4053380f4eecc8f4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { hash, compare } from 'bcrypt';
import { DbUser } from '#db/schemas/index.js';
import { RegisterDto } from '#dto/auth/index.js';

/**
 * @param data {RegisterDto}
 * @returns {Promise<(Error | HydratedDocument<InferSchemaType<module:mongoose.Schema>, ObtainSchemaGeneric<module:mongoose.Schema, "TVirtuals"> & ObtainSchemaGeneric<module:mongoose.Schema, "TInstanceMethods">, ObtainSchemaGeneric<module:mongoose.Schema, "TQueryHelpers">, ObtainSchemaGeneric<module:mongoose.Schema, "TVirtuals">>)[]>}
 */
export async function registerUser(data) {
    if (!(data instanceof RegisterDto))
        throw new Error('Invalid data type. Expected RegisterDto.');

    const passwordHash = await hash(data.password, 10);
    if (!passwordHash) {
        throw new Error('Failed to hash password.');
    }

    return DbUser.create({
        username: data.username,
        passwordHash,
        email: data.email,
        type: data.type
    });
}

export async function deleteUser(id, password) {
    const user = await DbUser.findById(id);
    DbUser.exists({ _id: id }).then(exists => {
        if (!exists) {
            throw new Error('User does not exist.');
        }
    });
    if (!user) {
        throw new Error('User not found.');
    }

    const isPasswordValid = await compare(password, user.passwordHash);
    if (!isPasswordValid) {
        throw new Error('Invalid password.');
    }

    await DbUser.findByIdAndDelete(id);
}