From 99220d73469210f94493ef92a9edc64ab50eb0d9 Mon Sep 17 00:00:00 2001 From: Rory& Date: Sun, 1 Jun 2025 01:03:40 +0200 Subject: Add some tests --- src/db/dbAccess/user.js | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/db/dbAccess/user.js (limited to 'src/db/dbAccess/user.js') 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); +} -- cgit 1.5.1