summary refs log tree commit diff
path: root/src/db/dbAccess/user.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/db/dbAccess/user.js')
-rw-r--r--src/db/dbAccess/user.js41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/db/dbAccess/user.js b/src/db/dbAccess/user.js
new file mode 100644

index 0000000..413b1cf --- /dev/null +++ b/src/db/dbAccess/user.js
@@ -0,0 +1,41 @@ +import { hash, compare } from 'bcrypt'; +import { DbUser } from '#db/schemas/index.js'; + +export async function registerUser(username, password, email, type = 'user') { + if (!username || !password || !email) { + throw new Error( + 'Username, password, and email are required to register a user.' + ); + } + + const passwordHash = await hash(password, 10); + if (!passwordHash) { + throw new Error('Failed to hash password.'); + } + + return DbUser.create({ + username, + passwordHash, + email, + 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); +}