since3-portal/modules/loginPage/actions/auth.ts
2026-09-29 21:47:44 +02:00

63 lines
No EOL
1.9 KiB
TypeScript

"use server";
import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import * as z from "zod";
import { createClient } from "@/lib/supabase/server";
export type AuthState = { error: string } | undefined;
const LoginSchema = z.object({
email: z.email({ error: "Bitte eine gültige Email eingeben." }),
password: z.string().min(1, { error: "Passwort ist erforderlich." }),
});
export async function login(
_prevState: AuthState,
formData: FormData
): Promise<AuthState> {
const validatedFields = LoginSchema.safeParse({
email: formData.get("email"),
password: formData.get("password"),
});
if (!validatedFields.success) {
const { fieldErrors } = z.flattenError(validatedFields.error);
const message = fieldErrors.email?.[0] ?? fieldErrors.password?.[0] ?? "Bitte Email und Passwort ausfüllen.";
return { error: message }
}
const { email, password } = validatedFields.data;
const supabase = await createClient();
const { data: signInData, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
return { error: "Email oder Passwort ist falsch" }
}
const { data: profile, error: profileError } = await supabase
.from("profiles")
.select("role")
.eq("id", signInData.user.id)
.single()
if (profileError || !profile) {
return { error: "Profil konnte nicht geladen werden. Bitte kontaktiere den Support." }
}
// Zwischengespeicherte Seiten eines vorherigen Nutzers im selben Tab verwerfen.
revalidatePath("/", "layout")
redirect(profile.role === "admin" ? "/admin/dashboard" : "/client/dashboard")
}
export async function logout() {
const supabase = await createClient();
await supabase.auth.signOut();
revalidatePath("/", "layout");
redirect("/");
}