forked from fahrPool/fahrPool
feat: Akteur am Service-Client und Audit-Eintraege fuer Nutzeraktionen
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
20994b9f59
commit
18bea21ca8
|
|
@ -24,7 +24,7 @@ export async function speichereSmtp(formData: FormData): Promise<ActionResult> {
|
|||
const kontext = await ladeAdminKontext();
|
||||
if (!kontext.ok) return { success: false, error: kontext.error };
|
||||
|
||||
const admin = createAdminClient();
|
||||
const admin = createAdminClient(kontext.profilId);
|
||||
const bestehend = await ladeFirmenSmtp(admin, kontext.firma.id);
|
||||
|
||||
const validation = validateSmtpEingabe(
|
||||
|
|
@ -80,7 +80,7 @@ export async function speichereSmtp(formData: FormData): Promise<ActionResult> {
|
|||
export async function entferneSmtp(): Promise<ActionResult> {
|
||||
const kontext = await ladeAdminKontext();
|
||||
if (!kontext.ok) return { success: false, error: kontext.error };
|
||||
const { error } = await createAdminClient().from("firmen_smtp").delete().eq("firma_id", kontext.firma.id);
|
||||
const { error } = await createAdminClient(kontext.profilId).from("firmen_smtp").delete().eq("firma_id", kontext.firma.id);
|
||||
if (error) return { success: false, error: "SMTP-Einstellungen konnten nicht entfernt werden." };
|
||||
revalidatePath("/firma");
|
||||
return { success: true };
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
import { validatePasswort } from "@/lib/auth/passwort";
|
||||
import { validateNutzerDetails, leseDetailsAusFormData } from "@/lib/nutzerverwaltung/details";
|
||||
import { speichereDetails } from "@/lib/nutzerverwaltung/details-queries";
|
||||
import { protokolliere } from "@/lib/audit/protokollieren";
|
||||
import { legeNutzerInFirmaAn } from "@/lib/nutzerverwaltung/nutzer-anlegen";
|
||||
import { pruefeZielNutzer } from "@/lib/nutzerverwaltung/ziel-pruefen";
|
||||
|
||||
|
|
@ -40,8 +41,9 @@ export async function erstelleNutzer(formData: FormData): Promise<void> {
|
|||
redirect(`/nutzerverwaltung?error=${encodeURIComponent(validation.error)}`);
|
||||
}
|
||||
|
||||
const ergebnis = await legeNutzerInFirmaAn(createAdminClient(), {
|
||||
const ergebnis = await legeNutzerInFirmaAn(createAdminClient(kontext.profilId), {
|
||||
firmaId: kontext.firma.id,
|
||||
akteurId: kontext.profilId,
|
||||
name: validation.name,
|
||||
email: validation.email,
|
||||
passwort: validation.passwort,
|
||||
|
|
@ -89,7 +91,7 @@ export async function aktualisiereNutzer(nutzerId: string, formData: FormData):
|
|||
return { success: false, error: "Die eigene Rolle kann nicht selbst geaendert werden." };
|
||||
}
|
||||
|
||||
const adminClient = createAdminClient();
|
||||
const adminClient = createAdminClient(profileResult.profile.id);
|
||||
const { data: aktuellerAuthUser } = await adminClient.auth.admin.getUserById(nutzerId);
|
||||
if (!aktuellerAuthUser.user) {
|
||||
return { success: false, error: "Nutzer nicht gefunden." };
|
||||
|
|
@ -103,6 +105,13 @@ export async function aktualisiereNutzer(nutzerId: string, formData: FormData):
|
|||
if (emailFehler) {
|
||||
return { success: false, error: `E-Mail konnte nicht geaendert werden: ${emailFehler.message}` };
|
||||
}
|
||||
await protokolliere(adminClient, {
|
||||
firmaId: profileResult.profile.firma_id,
|
||||
akteurId: profileResult.profile.id,
|
||||
aktion: "email_geaendert",
|
||||
nutzerId,
|
||||
aenderungen: { email: { alt: aktuellerAuthUser.user.email, neu: validation.email } },
|
||||
});
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
|
|
@ -142,11 +151,17 @@ export async function sperreNutzer(nutzerId: string): Promise<ActionResult> {
|
|||
return { success: false, error: NICHT_GEFUNDEN };
|
||||
}
|
||||
|
||||
const adminClient = createAdminClient();
|
||||
const adminClient = createAdminClient(profileResult.profile.id);
|
||||
const { error } = await adminClient.auth.admin.updateUserById(nutzerId, { ban_duration: "876000h" });
|
||||
if (error) {
|
||||
return { success: false, error: `Sperren fehlgeschlagen: ${error.message}` };
|
||||
}
|
||||
await protokolliere(adminClient, {
|
||||
firmaId: profileResult.profile.firma_id,
|
||||
akteurId: profileResult.profile.id,
|
||||
aktion: "nutzer_gesperrt",
|
||||
nutzerId,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
|
@ -162,11 +177,17 @@ export async function entsperreNutzer(nutzerId: string): Promise<ActionResult> {
|
|||
return { success: false, error: NICHT_GEFUNDEN };
|
||||
}
|
||||
|
||||
const adminClient = createAdminClient();
|
||||
const adminClient = createAdminClient(profileResult.profile.id);
|
||||
const { error } = await adminClient.auth.admin.updateUserById(nutzerId, { ban_duration: "none" });
|
||||
if (error) {
|
||||
return { success: false, error: `Entsperren fehlgeschlagen: ${error.message}` };
|
||||
}
|
||||
await protokolliere(adminClient, {
|
||||
firmaId: profileResult.profile.firma_id,
|
||||
akteurId: profileResult.profile.id,
|
||||
aktion: "nutzer_entsperrt",
|
||||
nutzerId,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
|
@ -191,7 +212,7 @@ export async function setzePasswort(nutzerId: string, formData: FormData): Promi
|
|||
return { success: false, error: NICHT_GEFUNDEN };
|
||||
}
|
||||
|
||||
const adminClient = createAdminClient();
|
||||
const adminClient = createAdminClient(profileResult.profile.id);
|
||||
const { error } = await adminClient.auth.admin.updateUserById(nutzerId, {
|
||||
password: validation.passwort,
|
||||
app_metadata: { must_change_password: true },
|
||||
|
|
@ -199,6 +220,12 @@ export async function setzePasswort(nutzerId: string, formData: FormData): Promi
|
|||
if (error) {
|
||||
return { success: false, error: `Passwort setzen fehlgeschlagen: ${error.message}` };
|
||||
}
|
||||
await protokolliere(adminClient, {
|
||||
firmaId: profileResult.profile.firma_id,
|
||||
akteurId: profileResult.profile.id,
|
||||
aktion: "passwort_gesetzt",
|
||||
nutzerId,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { revalidatePath } from "next/cache";
|
|||
import { createAdminClient } from "@/lib/supabase/admin";
|
||||
import { loadProfile } from "@/lib/auth/profile";
|
||||
import { validatePasswort } from "@/lib/auth/passwort";
|
||||
import { protokolliere } from "@/lib/audit/protokollieren";
|
||||
import { legeNutzerInFirmaAn } from "@/lib/nutzerverwaltung/nutzer-anlegen";
|
||||
import { pruefeSuperadmin } from "@/lib/plattform/superadmin";
|
||||
import { validateFirmaAnlegen, validateFirmenAdmin } from "@/lib/plattform/validate";
|
||||
|
|
@ -13,14 +14,16 @@ function zurueck(pfad: string, fehler?: string): never {
|
|||
redirect(fehler ? `${pfad}?error=${encodeURIComponent(fehler)}` : pfad);
|
||||
}
|
||||
|
||||
async function sicherSuperadmin(): Promise<void> {
|
||||
if (!pruefeSuperadmin(await loadProfile())) {
|
||||
async function sicherSuperadmin(): Promise<string> {
|
||||
const profil = await loadProfile();
|
||||
if (!pruefeSuperadmin(profil) || profil.status !== "ok") {
|
||||
redirect("/login");
|
||||
}
|
||||
return profil.profile.id;
|
||||
}
|
||||
|
||||
export async function legeFirmaAn(formData: FormData): Promise<void> {
|
||||
await sicherSuperadmin();
|
||||
const superadminId = await sicherSuperadmin();
|
||||
const v = validateFirmaAnlegen({
|
||||
firmenname: formData.get("firmenname"),
|
||||
name: formData.get("name"),
|
||||
|
|
@ -29,11 +32,11 @@ export async function legeFirmaAn(formData: FormData): Promise<void> {
|
|||
});
|
||||
if (!v.valid) zurueck("/plattform", v.error);
|
||||
|
||||
const admin = createAdminClient();
|
||||
const admin = createAdminClient(superadminId);
|
||||
const { data: firma, error } = await admin.from("firmen").insert({ name: v.firmenname }).select("id").single();
|
||||
if (error || !firma) zurueck("/plattform", "Firma konnte nicht angelegt werden.");
|
||||
|
||||
const nutzer = await legeNutzerInFirmaAn(admin, { firmaId: firma.id, rolle: "admin", ...v.admin });
|
||||
const nutzer = await legeNutzerInFirmaAn(admin, { firmaId: firma.id, rolle: "admin", akteurId: superadminId, ...v.admin });
|
||||
if (!nutzer.ok) {
|
||||
// Keine Firma ohne Admin zuruecklassen.
|
||||
const { error: loeschFehler } = await admin.from("firmen").delete().eq("id", firma.id);
|
||||
|
|
@ -47,18 +50,19 @@ export async function legeFirmaAn(formData: FormData): Promise<void> {
|
|||
}
|
||||
|
||||
export async function setzeFirmaAktiv(firmaId: string, aktiv: boolean): Promise<void> {
|
||||
await sicherSuperadmin();
|
||||
const { error } = await createAdminClient().from("firmen").update({ aktiv }).eq("id", firmaId);
|
||||
const superadminId = await sicherSuperadmin();
|
||||
const { error } = await createAdminClient(superadminId).from("firmen").update({ aktiv }).eq("id", firmaId);
|
||||
revalidatePath("/plattform");
|
||||
zurueck(`/plattform/${firmaId}`, error ? "Status konnte nicht geändert werden." : undefined);
|
||||
}
|
||||
|
||||
export async function legeFirmenAdminAn(firmaId: string, formData: FormData): Promise<void> {
|
||||
await sicherSuperadmin();
|
||||
const superadminId = await sicherSuperadmin();
|
||||
const v = validateFirmenAdmin({ name: formData.get("name"), email: formData.get("email"), passwort: formData.get("passwort") });
|
||||
if (!v.valid) zurueck(`/plattform/${firmaId}`, v.error);
|
||||
const nutzer = await legeNutzerInFirmaAn(createAdminClient(), {
|
||||
const nutzer = await legeNutzerInFirmaAn(createAdminClient(superadminId), {
|
||||
firmaId,
|
||||
akteurId: superadminId,
|
||||
rolle: "admin",
|
||||
name: v.name,
|
||||
email: v.email,
|
||||
|
|
@ -68,11 +72,11 @@ export async function legeFirmenAdminAn(firmaId: string, formData: FormData): Pr
|
|||
}
|
||||
|
||||
export async function setzeAdminPasswort(firmaId: string, nutzerId: string, formData: FormData): Promise<void> {
|
||||
await sicherSuperadmin();
|
||||
const superadminId = await sicherSuperadmin();
|
||||
const v = validatePasswort(formData.get("passwort"));
|
||||
if (!v.valid) zurueck(`/plattform/${firmaId}`, v.error);
|
||||
|
||||
const admin = createAdminClient();
|
||||
const admin = createAdminClient(superadminId);
|
||||
// Nur Admins der angegebenen Firma, nie andere Rollen oder Superadmins.
|
||||
const { data: ziel } = await admin
|
||||
.from("profiles")
|
||||
|
|
@ -87,5 +91,8 @@ export async function setzeAdminPasswort(firmaId: string, nutzerId: string, form
|
|||
password: v.passwort,
|
||||
app_metadata: { must_change_password: true },
|
||||
});
|
||||
if (!error) {
|
||||
await protokolliere(admin, { firmaId, akteurId: superadminId, aktion: "passwort_gesetzt", nutzerId });
|
||||
}
|
||||
zurueck(`/plattform/${firmaId}`, error ? `Passwort setzen fehlgeschlagen: ${error.message}` : undefined);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { protokolliere } from "./protokollieren";
|
||||
|
||||
describe("protokolliere", () => {
|
||||
it("ruft die RPC mit den richtigen Parametern", async () => {
|
||||
const rpc = vi.fn(async () => ({ error: null }));
|
||||
await protokolliere({ rpc } as unknown as SupabaseClient, {
|
||||
firmaId: "f1",
|
||||
akteurId: "a1",
|
||||
aktion: "nutzer_gesperrt",
|
||||
nutzerId: "n1",
|
||||
});
|
||||
expect(rpc).toHaveBeenCalledWith("audit_protokollieren", {
|
||||
p_firma_id: "f1",
|
||||
p_akteur_id: "a1",
|
||||
p_bereich: "nutzer",
|
||||
p_aktion: "nutzer_gesperrt",
|
||||
p_datensatz_id: "n1",
|
||||
p_aenderungen: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("schluckt RPC-Fehler und loggt sie", async () => {
|
||||
const fehler = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const rpc = vi.fn(async () => ({ error: { message: "kaputt" } }));
|
||||
await expect(
|
||||
protokolliere({ rpc } as unknown as SupabaseClient, {
|
||||
firmaId: null,
|
||||
akteurId: null,
|
||||
aktion: "passwort_gesetzt",
|
||||
nutzerId: "n1",
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
expect(fehler).toHaveBeenCalled();
|
||||
fehler.mockRestore();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
|
||||
export type ProtokollAktion =
|
||||
| "nutzer_angelegt"
|
||||
| "nutzer_gesperrt"
|
||||
| "nutzer_entsperrt"
|
||||
| "passwort_gesetzt"
|
||||
| "email_geaendert";
|
||||
|
||||
export type ProtokollEintrag = {
|
||||
firmaId: string | null;
|
||||
akteurId: string | null;
|
||||
aktion: ProtokollAktion;
|
||||
nutzerId: string;
|
||||
aenderungen?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
// Fuer Aktionen des Auth-Dienstes, die keine Tabellenaenderung sind. Die Aktion
|
||||
// ist zu diesem Zeitpunkt schon passiert: ein Protokollfehler wird geloggt,
|
||||
// laesst sie aber nicht nachtraeglich scheitern. Nie Passwoerter uebergeben.
|
||||
export async function protokolliere(admin: SupabaseClient, e: ProtokollEintrag): Promise<void> {
|
||||
const { error } = await admin.rpc("audit_protokollieren", {
|
||||
p_firma_id: e.firmaId,
|
||||
p_akteur_id: e.akteurId,
|
||||
p_bereich: "nutzer",
|
||||
p_aktion: e.aktion,
|
||||
p_datensatz_id: e.nutzerId,
|
||||
p_aenderungen: e.aenderungen ?? {},
|
||||
});
|
||||
if (error) {
|
||||
console.error("[audit] Protokolleintrag fehlgeschlagen:", e.aktion, e.nutzerId, error.message);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,7 +7,9 @@ type Fehler = { code?: string; message: string } | null;
|
|||
function fakeAdmin(opts: { createFehler?: string; zuordnungFehler?: Fehler; usernameFehler?: Fehler }) {
|
||||
const updates: Record<string, unknown>[] = [];
|
||||
const deleteUser = vi.fn(async () => ({ error: null }));
|
||||
const rpc = vi.fn(async (..._args: unknown[]) => ({ error: null }));
|
||||
const client = {
|
||||
rpc,
|
||||
auth: {
|
||||
admin: {
|
||||
createUser: vi.fn(async () =>
|
||||
|
|
@ -28,11 +30,12 @@ function fakeAdmin(opts: { createFehler?: string; zuordnungFehler?: Fehler; user
|
|||
}),
|
||||
}),
|
||||
} as unknown as SupabaseClient;
|
||||
return { client, updates, deleteUser };
|
||||
return { client, updates, deleteUser, rpc };
|
||||
}
|
||||
|
||||
const EINGABE = {
|
||||
firmaId: "f2",
|
||||
akteurId: "akteur-1",
|
||||
name: "Neu",
|
||||
email: "neu@test.local",
|
||||
passwort: "Passwort123!",
|
||||
|
|
@ -47,6 +50,25 @@ describe("legeNutzerInFirmaAn", () => {
|
|||
expect(updates).toEqual([{ firma_id: "f2", role: "fahrer" }, { username: "neu.fahrer" }]);
|
||||
});
|
||||
|
||||
it("protokolliert nutzer_angelegt nach erfolgreicher Anlage", async () => {
|
||||
const { client, rpc } = fakeAdmin({});
|
||||
await legeNutzerInFirmaAn(client, EINGABE);
|
||||
expect(rpc).toHaveBeenCalledWith("audit_protokollieren", {
|
||||
p_firma_id: "f2",
|
||||
p_akteur_id: "akteur-1",
|
||||
p_bereich: "nutzer",
|
||||
p_aktion: "nutzer_angelegt",
|
||||
p_datensatz_id: "neu",
|
||||
p_aenderungen: { email: "neu@test.local", rolle: "fahrer" },
|
||||
});
|
||||
});
|
||||
|
||||
it("protokolliert nicht, wenn die Zuordnung scheitert", async () => {
|
||||
const { client, rpc } = fakeAdmin({ zuordnungFehler: { message: "kaputt" } });
|
||||
await legeNutzerInFirmaAn(client, EINGABE);
|
||||
expect(rpc).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("meldet den Fehler von createUser", async () => {
|
||||
const { client } = fakeAdmin({ createFehler: "exists" });
|
||||
expect(await legeNutzerInFirmaAn(client, EINGABE)).toEqual({ ok: false, fehler: "Nutzer anlegen fehlgeschlagen: exists" });
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { protokolliere } from "@/lib/audit/protokollieren";
|
||||
|
||||
export type NutzerAnlegenEingabe = {
|
||||
firmaId: string;
|
||||
akteurId: string;
|
||||
name: string;
|
||||
email: string;
|
||||
passwort: string;
|
||||
|
|
@ -42,6 +44,14 @@ export async function legeNutzerInFirmaAn(
|
|||
return { ok: false, fehler: `Nutzer konnte keiner Firma zugeordnet werden: ${zuordnungFehler.message}` };
|
||||
}
|
||||
|
||||
await protokolliere(admin, {
|
||||
firmaId: e.firmaId,
|
||||
akteurId: e.akteurId,
|
||||
aktion: "nutzer_angelegt",
|
||||
nutzerId: id,
|
||||
aenderungen: { email: e.email, rolle: e.rolle },
|
||||
});
|
||||
|
||||
if (!e.username) {
|
||||
return { ok: true, id, usernameHinweis: null };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const createClient = vi.fn((..._args: unknown[]) => ({}));
|
||||
vi.mock("@supabase/supabase-js", () => ({ createClient }));
|
||||
|
||||
describe("createAdminClient", () => {
|
||||
beforeEach(() => {
|
||||
createClient.mockClear();
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL = "http://supabase.test";
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = "service-key";
|
||||
});
|
||||
|
||||
it("setzt ohne Akteur keinen Audit-Header", async () => {
|
||||
const { createAdminClient } = await import("./admin");
|
||||
createAdminClient();
|
||||
const optionen = createClient.mock.calls[0][2] as { global?: unknown };
|
||||
expect(optionen.global).toBeUndefined();
|
||||
});
|
||||
|
||||
it("setzt mit Akteur den Header x-audit-akteur", async () => {
|
||||
const { createAdminClient } = await import("./admin");
|
||||
createAdminClient("11111111-1111-1111-1111-111111111111");
|
||||
const optionen = createClient.mock.calls[0][2] as { global: { headers: Record<string, string> } };
|
||||
expect(optionen.global.headers["x-audit-akteur"]).toBe("11111111-1111-1111-1111-111111111111");
|
||||
});
|
||||
});
|
||||
|
|
@ -5,7 +5,10 @@ import { createClient } from "@supabase/supabase-js";
|
|||
// sich direkt ueber den Service-Role-Key und darf niemals im Browser
|
||||
// landen. SUPABASE_INTERNAL_URL-Fallback aus demselben Grund wie in
|
||||
// server.ts: im Docker-Container zeigt "localhost" auf den Container selbst.
|
||||
export function createAdminClient() {
|
||||
// akteurId: Profil-ID des Nutzers, in dessen Namen die Server Action schreibt.
|
||||
// Die Datenbank uebernimmt sie fuer das Audit-Log (Header x-audit-akteur, nur
|
||||
// beim Service-Client vertrauenswuerdig, siehe public.audit_akteur_id()).
|
||||
export function createAdminClient(akteurId?: string) {
|
||||
return createClient(
|
||||
process.env.SUPABASE_INTERNAL_URL ?? process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
|
|
@ -14,6 +17,7 @@ export function createAdminClient() {
|
|||
autoRefreshToken: false,
|
||||
persistSession: false,
|
||||
},
|
||||
...(akteurId ? { global: { headers: { "x-audit-akteur": akteurId } } } : {}),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue