push
This commit is contained in:
66
innungsapp/apps/admin/app/[slug]/actions.ts
Normal file
66
innungsapp/apps/admin/app/[slug]/actions.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
'use server'
|
||||
|
||||
import { auth, getSanitizedHeaders } from '@/lib/auth'
|
||||
import { prisma } from '@innungsapp/shared'
|
||||
import { headers } from 'next/headers'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import { redirect } from 'next/navigation'
|
||||
|
||||
export async function changePasswordAndDisableMustChange(prevState: any, formData: FormData) {
|
||||
const currentPassword = formData.get('currentPassword') as string
|
||||
const newPassword = formData.get('newPassword') as string
|
||||
const confirmPassword = formData.get('confirmPassword') as string
|
||||
|
||||
if (newPassword !== confirmPassword) {
|
||||
return { success: false, error: 'Passwörter stimmen nicht überein.' }
|
||||
}
|
||||
|
||||
if (newPassword.length < 8) {
|
||||
return { success: false, error: 'Das Passwort muss mindestens 8 Zeichen lang sein.' }
|
||||
}
|
||||
|
||||
const sanitizedHeaders = await getSanitizedHeaders()
|
||||
const session = await auth.api.getSession({ headers: sanitizedHeaders })
|
||||
if (!session?.user) {
|
||||
return { success: false, error: 'Nicht authentifiziert.' }
|
||||
}
|
||||
|
||||
let redirectUrl: string | null = null
|
||||
|
||||
try {
|
||||
// Update password using better-auth
|
||||
// This will throw if the current password is invalid or other error occurs
|
||||
await auth.api.changePassword({
|
||||
headers: sanitizedHeaders,
|
||||
body: {
|
||||
newPassword,
|
||||
currentPassword,
|
||||
}
|
||||
})
|
||||
|
||||
// Update mustChangePassword flag in database
|
||||
await prisma.user.update({
|
||||
where: { id: session.user.id },
|
||||
data: { mustChangePassword: false }
|
||||
})
|
||||
|
||||
const slug = formData.get('slug') as string
|
||||
|
||||
// Sign out so the user has to re-login with the new password
|
||||
await auth.api.signOut({ headers: sanitizedHeaders })
|
||||
|
||||
redirectUrl = `/login?message=password_changed&callbackUrl=/${slug}/dashboard`
|
||||
} catch (e: any) {
|
||||
console.error('Password reset exception:', e)
|
||||
// BetterAuth errors often have a message or code
|
||||
const errorMessage = e?.message?.toLowerCase() || ''
|
||||
if (errorMessage.includes('invalid') && errorMessage.includes('password')) {
|
||||
return { success: false, error: 'Das aktuelle Passwort ist nicht korrekt.' }
|
||||
}
|
||||
return { success: false, error: 'Ein unerwarteter Fehler ist aufgetreten.' }
|
||||
}
|
||||
|
||||
if (redirectUrl) {
|
||||
redirect(redirectUrl)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user