Feat: Add Change Password
增加修改密码功能
This commit is contained in:
@@ -28,4 +28,34 @@ export default async function authRoutes(fastify) {
|
||||
return reply.code(401).send({ error: "Not authenticated" });
|
||||
return { id: request.session.userId, username: request.session.username };
|
||||
});
|
||||
|
||||
fastify.post("/api/auth/change-username", async (request, reply) => {
|
||||
const { new_username } = request.body ?? {};
|
||||
if (!new_username?.trim())
|
||||
return reply.code(400).send({ error: "new_username required" });
|
||||
|
||||
const existing = db.prepare("SELECT id FROM users WHERE username = ?").get(new_username.trim());
|
||||
if (existing)
|
||||
return reply.code(409).send({ error: "Username already taken" });
|
||||
|
||||
db.prepare("UPDATE users SET username = ? WHERE id = ?").run(new_username.trim(), request.session.userId);
|
||||
request.session.username = new_username.trim();
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
fastify.post("/api/auth/change-password", async (request, reply) => {
|
||||
const { current_password, new_password } = request.body ?? {};
|
||||
if (!current_password || !new_password)
|
||||
return reply.code(400).send({ error: "current_password and new_password required" });
|
||||
if (new_password.length < 6)
|
||||
return reply.code(400).send({ error: "new_password must be at least 6 characters" });
|
||||
|
||||
const user = db.prepare("SELECT * FROM users WHERE id = ?").get(request.session.userId);
|
||||
if (!user || !(await bcrypt.compare(current_password, user.password_hash)))
|
||||
return reply.code(401).send({ error: "Current password is incorrect" });
|
||||
|
||||
const hash = await bcrypt.hash(new_password, 10);
|
||||
db.prepare("UPDATE users SET password_hash = ? WHERE id = ?").run(hash, user.id);
|
||||
return { ok: true };
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user