Files
PAGIVA/src/app/api/auth/change-password/route.ts
T
Loma Bot Ops 4a673ebb28 Support sub-path deploy via NEXT_PUBLIC_BASE_PATH (loma.chat/pagiva)
Adds basePath config, withBase/appUrl helpers, base-path-aware cookies,
OAuth redirects, manifest, service worker and cron runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:48:42 +07:00

48 lines
1.7 KiB
TypeScript

import { BASE_PATH } from "@/lib/base-path";
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireUser } from "@/lib/auth/user";
import { createSessionToken, COOKIE_NAME, SESSION_DURATION_SECONDS } from "@/lib/auth/session";
import { hashPassword, passwordProblem, verifyPassword } from "@/lib/auth/password";
export async function POST(req: Request) {
const auth = await requireUser();
if (!auth.ok) return auth.response;
const body = await req.json().catch(() => null);
const currentPassword = typeof body?.currentPassword === "string" ? body.currentPassword : "";
const newPassword = typeof body?.newPassword === "string" ? body.newPassword : "";
const user = await prisma.user.findUniqueOrThrow({ where: { id: auth.user.id } });
if (!(await verifyPassword(currentPassword, user.passwordHash))) {
return NextResponse.json({ error: "รหัสผ่านปัจจุบันไม่ถูกต้อง" }, { status: 400 });
}
const problem = passwordProblem(newPassword);
if (problem) return NextResponse.json({ error: problem }, { status: 400 });
await prisma.user.update({
where: { id: user.id },
data: { passwordHash: await hashPassword(newPassword), mustChangePassword: false },
});
const token = await createSessionToken({
userId: user.id,
email: user.email,
name: user.name,
role: user.globalRole,
mustChangePassword: false,
});
const res = NextResponse.json({ ok: true });
res.cookies.set(COOKIE_NAME, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
path: BASE_PATH || "/",
maxAge: SESSION_DURATION_SECONDS,
});
return res;
}