import { NextResponse } from "next/server"; import { query, queryOne } from "@/lib/db"; import { hashPassword, verifyPassword } from "@/lib/auth/password"; import { requireSession, UnauthorizedError } from "@/lib/auth/session"; import { isSameOrigin } from "@/lib/origin"; export async function PATCH(request: Request) { if (!isSameOrigin(request)) { return NextResponse.json({ error: "Nicht erlaubt." }, { status: 403 }); } try { const session = await requireSession(); const { currentPassword, newPassword } = (await request.json().catch(() => ({}))) as { currentPassword?: string; newPassword?: string; }; if (!currentPassword || !newPassword || newPassword.length < 8) { return NextResponse.json({ error: "invalid_input" }, { status: 400 }); } const user = await queryOne<{ password_hash: string }>( "select password_hash from users where id = $1", [session.user.id] ); if (!user || !verifyPassword(currentPassword, user.password_hash)) { return NextResponse.json({ error: "wrong_password" }, { status: 401 }); } await query("update users set password_hash = $1 where id = $2", [ hashPassword(newPassword), session.user.id, ]); return NextResponse.json({ ok: true }); } catch (err) { if (err instanceof UnauthorizedError) { return NextResponse.json({ error: "unauthorized" }, { status: 401 }); } throw err; } }