19 lines
1.3 KiB
TypeScript
19 lines
1.3 KiB
TypeScript
import bcrypt from "bcryptjs";
|
|
import { NextResponse } from "next/server";
|
|
import { requireUser } from "@/lib/auth";
|
|
import { db } from "@/lib/db";
|
|
import { externalUrl } from "@/lib/http";
|
|
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const user = await requireUser(); const form = await req.formData();
|
|
const currentPassword = String(form.get("currentPassword") || ""); const newPassword = String(form.get("newPassword") || ""); const confirmPassword = String(form.get("confirmPassword") || "");
|
|
if (newPassword.length < 10) throw new Error("新密碼至少需要 10 個字元");
|
|
if (newPassword !== confirmPassword) throw new Error("兩次新密碼不一致");
|
|
const account = db.prepare("SELECT password_hash FROM users WHERE id=? AND disabled=0").get(user.id) as { password_hash: string } | undefined;
|
|
if (!account || !(await bcrypt.compare(currentPassword, account.password_hash))) throw new Error("目前密碼不正確");
|
|
db.prepare("UPDATE users SET password_hash=? WHERE id=?").run(await bcrypt.hash(newPassword, 12), user.id);
|
|
return NextResponse.redirect(externalUrl(req, "/account?updated=1"));
|
|
} catch (error) { return NextResponse.redirect(externalUrl(req, "/account?error=" + encodeURIComponent(error instanceof Error ? error.message : "password"))); }
|
|
}
|