1
0
Fork 0
fahrPool/web/app/login/actions.ts

89 lines
2.9 KiB
TypeScript

"use server";
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { createAdminClient } from "@/lib/supabase/admin";
import { PASSWORT_AENDERN_PFAD, hatPasswortAenderPflicht } from "@/lib/auth/passwort";
import { pruefeFirmenzugang } from "@/lib/firma/queries";
import { FIRMA_GESPERRT } from "@/lib/firma/eigene-firma";
import { validateLogin } from "@/lib/validate-login";
const LOGIN_FEHLER = "E-Mail oder Passwort ist falsch.";
const LOGIN_NICHT_MOEGLICH = "Anmeldung derzeit nicht möglich. Bitte später erneut versuchen.";
export async function login(formData: FormData): Promise<void> {
const validation = validateLogin({
identifier: formData.get("identifier"),
password: formData.get("password"),
});
if (!validation.valid) {
redirect(`/login?error=${encodeURIComponent(validation.error)}`);
}
let email = validation.identifier;
if (!email.includes("@")) {
// Service-Role-Lookup noetig: profiles ist per RLS vor dem Login nicht
// lesbar. Absichtlich derselbe generische Fehler wie bei falschem
// Passwort (kein "Benutzername nicht gefunden"), damit sich nicht per
// Fehlermeldung durchprobieren laesst, welche Benutzernamen existieren.
const adminClient = createAdminClient();
const { data: profil, error: profilFehler } = await adminClient
.from("profiles")
.select("id")
.eq("username", email.toLowerCase())
.maybeSingle();
if (profilFehler) {
console.error("Benutzername-Lookup beim Login fehlgeschlagen:", profilFehler);
}
if (!profil) {
redirect(`/login?error=${encodeURIComponent(LOGIN_FEHLER)}`);
}
const { data: authNutzer, error: nutzerFehler } = await adminClient.auth.admin.getUserById(profil.id);
if (nutzerFehler || !authNutzer.user?.email) {
redirect(`/login?error=${encodeURIComponent(LOGIN_FEHLER)}`);
}
email = authNutzer.user.email;
}
const supabase = await createClient();
const { data, error } = await supabase.auth.signInWithPassword({
email,
password: validation.password,
});
if (error) {
redirect(`/login?error=${encodeURIComponent(LOGIN_FEHLER)}`);
}
let zugang: Awaited<ReturnType<typeof pruefeFirmenzugang>> | null = null;
try {
zugang = await pruefeFirmenzugang(supabase, data.user.id);
} catch (e) {
console.error("Firmenzugang beim Login nicht pruefbar:", e);
}
if (zugang === null) {
await supabase.auth.signOut();
redirect(`/login?error=${encodeURIComponent(LOGIN_NICHT_MOEGLICH)}`);
}
if (zugang === "gesperrt") {
await supabase.auth.signOut();
redirect(`/login?error=${encodeURIComponent(FIRMA_GESPERRT)}`);
}
if (hatPasswortAenderPflicht(data.user)) {
redirect(PASSWORT_AENDERN_PFAD);
}
redirect(zugang === "superadmin" ? "/plattform" : "/dashboard");
}
export async function logout(): Promise<void> {
const supabase = await createClient();
await supabase.auth.signOut();
redirect("/login");
}