Add change password feature

This commit is contained in:
Szymon Nowakowski
2024-12-25 20:51:44 +01:00
parent 46763a95c1
commit 8ef3572e79
3 changed files with 136 additions and 4 deletions

View File

@@ -158,6 +158,45 @@ const app = new Elysia()
.execute();
})
.post("/change-password", async ({ db, body: { username, currentPassword, newPassword }, set }) => {
const user = await db
.selectFrom("User")
.selectAll()
.where("username", "=", username)
.executeTakeFirst();
if (user === undefined) {
return error("Unauthorized", "Invalid username or password");
}
const valid = await Bun.password.verify(currentPassword, user.password);
if (!valid) {
return error("Unauthorized", "Invalid username or password");
}
const password = await Bun.password.hash(newPassword);
const res = await db
.updateTable("User")
.set({ password })
.where("username", "=", username)
.returningAll()
.execute();
if (res.length === 0) {
return error("Unauthorized", "Invalid username or password");
}
set.status = "No Content";
}, {
body: t.Object({
username: t.String({ minLength: 1 }),
currentPassword: t.String({ minLength: 1 }),
newPassword: t.String({ minLength: 1 }),
}),
})
// --- MARK: USER MANAGEMENT -------------------------------------------
.get("/user/:userId", async ({ db, params: { userId }, user }) => {