summary refs log tree commit diff
path: root/src/db/dbAccess/user.js
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2025-06-01 01:03:40 +0200
committerRory& <root@rory.gay>2025-06-01 01:03:40 +0200
commit99220d73469210f94493ef92a9edc64ab50eb0d9 (patch)
tree765781a300db5c1e1a15afaa8bd09f48712a5313 /src/db/dbAccess/user.js
parentInit test frontend (diff)
downloadnodejs-final-assignment-99220d73469210f94493ef92a9edc64ab50eb0d9.tar.xz
Add some tests
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); +}