35 lines
1.3 KiB
TypeScript
35 lines
1.3 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { getServerSession } from "next-auth";
|
|
import bcrypt from "bcryptjs";
|
|
import { authOptions } from "@/lib/auth-options";
|
|
import { prisma } from "@/lib/prisma";
|
|
|
|
export async function POST(req: Request) {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401 });
|
|
}
|
|
|
|
const body = (await req.json().catch(() => null)) as {
|
|
currentPassword?: string;
|
|
newPassword?: string;
|
|
} | null;
|
|
|
|
const currentPassword = body?.currentPassword ?? "";
|
|
const newPassword = body?.newPassword ?? "";
|
|
if (!currentPassword || newPassword.length < 8) {
|
|
return NextResponse.json({ error: "Ungültige Eingaben." }, { status: 400 });
|
|
}
|
|
|
|
const user = await prisma.user.findUnique({ where: { id: session.user.id } });
|
|
if (!user) return NextResponse.json({ error: "Nutzer nicht gefunden." }, { status: 404 });
|
|
|
|
const ok = await bcrypt.compare(currentPassword, user.passwordHash);
|
|
if (!ok) return NextResponse.json({ error: "Aktuelles Passwort ist falsch." }, { status: 403 });
|
|
|
|
const passwordHash = await bcrypt.hash(newPassword, 10);
|
|
await prisma.user.update({ where: { id: user.id }, data: { passwordHash } });
|
|
|
|
return NextResponse.json({ ok: true });
|
|
}
|