MBO-Tech-IT-Webseite/modules/06-website-cms/files/app/api/admin/passwort/route.ts

31 lines
1.3 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import { requireAdmin } from '@/lib/admin-auth'
import { createServiceClient } from '@/lib/supabase'
export async function POST(req: NextRequest) {
const session = await requireAdmin()
if (session instanceof NextResponse) return session
const { currentPassword, newPassword } = await req.json()
if (!currentPassword || !newPassword) {
return NextResponse.json({ error: 'Alle Felder erforderlich.' }, { status: 400 })
}
if (newPassword.length < 8) {
return NextResponse.json({ error: 'Neues Passwort muss mindestens 8 Zeichen haben.' }, { status: 400 })
}
const db = createServiceClient()
const { data: admin } = await db.from('admins').select('password_hash').eq('id', session.id).single()
if (!admin) return NextResponse.json({ error: 'Admin nicht gefunden.' }, { status: 404 })
const ok = await bcrypt.compare(currentPassword, admin.password_hash)
if (!ok) return NextResponse.json({ error: 'Aktuelles Passwort ist falsch.' }, { status: 401 })
const hash = await bcrypt.hash(newPassword, 10)
const { error } = await db.from('admins').update({ password_hash: hash }).eq('id', session.id)
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
return NextResponse.json({ success: true })
}