forked from fahrPool/fahrPool
79 lines
2.5 KiB
TypeScript
79 lines
2.5 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.";
|
|
|
|
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)}`);
|
|
}
|
|
|
|
const zugang = await pruefeFirmenzugang(supabase, data.user.id);
|
|
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");
|
|
}
|