40 lines
1.9 KiB
TypeScript
40 lines
1.9 KiB
TypeScript
import { cookies } from "next/headers";
|
|
import PocketBase from "pocketbase";
|
|
import { initialDestination } from "@/lib/auth/access";
|
|
import { authMode, getCurrentUser, SESSION_COOKIE } from "@/lib/auth/session";
|
|
import { PB_URL, pbAdmin } from "@/lib/pb";
|
|
import { SESSION_MAX_AGE_SECONDS } from "@/lib/auth/session-policy";
|
|
|
|
export async function POST(request: Request): Promise<Response> {
|
|
if (authMode() !== "users") return Response.json({ error: "Not found" }, { status: 404 });
|
|
const user = await getCurrentUser();
|
|
if (!user) return Response.json({ error: "Sign in required" }, { status: 401 });
|
|
if (!user.mustChangePassword) return Response.json({ error: "Password change not required" }, { status: 403 });
|
|
|
|
let body: Record<string, unknown>;
|
|
try { body = await request.json(); }
|
|
catch { return Response.json({ error: "Enter and confirm your new password" }, { status: 400 }); }
|
|
const password = typeof body.password === "string" ? body.password : "";
|
|
const passwordConfirm = typeof body.passwordConfirm === "string" ? body.passwordConfirm : "";
|
|
if (password.length < 10 || password.length > 128 || password !== passwordConfirm) {
|
|
return Response.json({ error: "Use at least 10 characters and confirm the same password" }, { status: 400 });
|
|
}
|
|
|
|
try {
|
|
await (await pbAdmin()).collection("users").update(user.id, {
|
|
password, passwordConfirm, must_change_password: false,
|
|
});
|
|
const pb = new PocketBase(PB_URL);
|
|
await pb.collection("users").authWithPassword(user.email, password);
|
|
(await cookies()).set(SESSION_COOKIE, pb.authStore.token, {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === "production",
|
|
sameSite: "lax",
|
|
path: "/",
|
|
maxAge: SESSION_MAX_AGE_SECONDS,
|
|
});
|
|
return Response.json({ landing: initialDestination({ ...user, mustChangePassword: false }) });
|
|
} catch {
|
|
return Response.json({ error: "Could not save your password. Try again." }, { status: 500 });
|
|
}
|
|
}
|