diff --git a/.env.example b/.env.example index 71df0fe..2d34257 100644 --- a/.env.example +++ b/.env.example @@ -32,7 +32,6 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY= # Dispatch-Route antwortet dann 200 { uebersprungen: true } und sendet nichts. WHATSAPP_ACCESS_TOKEN= WHATSAPP_PHONE_NUMBER_ID= -WHATSAPP_RECIPIENT= WHATSAPP_TEMPLATE_NAME=neuer_auftrag WHATSAPP_TEMPLATE_LANG=de WHATSAPP_GRAPH_VERSION= @@ -52,3 +51,7 @@ SMTP_SECURE=false SMTP_USER= SMTP_PASSWORD= SMTP_FROM= + +# Schluessel fuer die SMTP-Passwoerter der Firmen (AES-256-GCM, 32 Byte base64). +# Erzeugen: openssl rand -base64 32 (Aendern macht gespeicherte Passwoerter unlesbar) +SMTP_VERSCHLUESSELUNG_KEY= diff --git a/README.md b/README.md index 5d1a02a..f0dbf4d 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,17 @@ Ein Admin muss die Rolle danach explizit setzen: select name, role from public.profiles; ``` +## 6a. Plattform-Betreiber (Superadmin) anlegen + +Der Superadmin legt Firmen und deren erste Admins an (`/plattform`), sieht aber keine Aufträge. +Einmalig aus `web/`: + + SUPABASE_URL=http://localhost:8000 SUPABASE_SERVICE_ROLE_KEY= \ + node scripts/superadmin-anlegen.mjs superadmin@example.de '' 'Plattform' + +Für die SMTP-Zugänge der Firmen muss `SMTP_VERSCHLUESSELUNG_KEY` in der `.env` gesetzt sein +(`openssl rand -base64 32`). Der WhatsApp-Empfänger wird pro Firma unter `/firma` eingetragen. + ## 7. Lokale Entwicklung ohne Docker fuer `web/` (Alternative zu Schritt 4) Der `web`-Service kann auch ausserhalb von Docker laufen, waehrend der diff --git a/docker-compose.yaml b/docker-compose.yaml index 33921f9..45fdb6f 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -185,7 +185,6 @@ services: # fuenf WHATSAPP_*-Pflichtvariablen, ueberspringt der Dispatcher sauber. WHATSAPP_ACCESS_TOKEN: ${WHATSAPP_ACCESS_TOKEN} WHATSAPP_PHONE_NUMBER_ID: ${WHATSAPP_PHONE_NUMBER_ID} - WHATSAPP_RECIPIENT: ${WHATSAPP_RECIPIENT} WHATSAPP_TEMPLATE_NAME: ${WHATSAPP_TEMPLATE_NAME} WHATSAPP_TEMPLATE_LANG: ${WHATSAPP_TEMPLATE_LANG} WHATSAPP_GRAPH_VERSION: ${WHATSAPP_GRAPH_VERSION} @@ -199,3 +198,4 @@ services: SMTP_USER: ${SMTP_USER} SMTP_PASSWORD: ${SMTP_PASSWORD} SMTP_FROM: ${SMTP_FROM} + SMTP_VERSCHLUESSELUNG_KEY: ${SMTP_VERSCHLUESSELUNG_KEY} diff --git a/supabase/migrations/20261012090000_superadmin_rolle.sql b/supabase/migrations/20261012090000_superadmin_rolle.sql new file mode 100644 index 0000000..981f999 --- /dev/null +++ b/supabase/migrations/20261012090000_superadmin_rolle.sql @@ -0,0 +1,3 @@ +-- Eigene Migration: ein neuer Enum-Wert ist erst nach dem Commit der +-- Transaktion verwendbar, die ihn anlegt (die Folgemigration nutzt ihn). +alter type public.app_role add value if not exists 'superadmin'; diff --git a/supabase/migrations/20261012090100_mandanten_struktur.sql b/supabase/migrations/20261012090100_mandanten_struktur.sql new file mode 100644 index 0000000..f38db09 --- /dev/null +++ b/supabase/migrations/20261012090100_mandanten_struktur.sql @@ -0,0 +1,411 @@ +-- Mandantenfaehigkeit, Teil 1: Firmen, firma_id in allen Fachtabellen, +-- Trigger zum Setzen/Schuetzen der firma_id, Eindeutigkeit pro Firma. +-- Die RLS-Policies folgen in 20261012090200_mandanten_rls.sql. + +-- ---------------------------------------------------------------- firmen +create table public.firmen ( + id uuid primary key default gen_random_uuid(), + name text not null, + aktiv boolean not null default true, + logo_pfad text, + whatsapp_empfaenger text, + farbe_primaer text, + farbe_dunkel text, + created_at timestamptz not null default now(), + constraint firmen_name_nicht_leer check (length(btrim(name)) > 0), + constraint firmen_whatsapp_e164 check (whatsapp_empfaenger is null or whatsapp_empfaenger ~ '^\+[1-9][0-9]{7,14}$'), + constraint firmen_farbe_primaer_hex check (farbe_primaer is null or farbe_primaer ~ '^#[0-9a-f]{6}$'), + constraint firmen_farbe_dunkel_hex check (farbe_dunkel is null or farbe_dunkel ~ '^#[0-9a-f]{6}$') +); + +alter table public.firmen enable row level security; +-- Supabase vergibt per Default-Privileges alle Rechte an anon/authenticated +-- (siehe information_schema.role_table_grants). Explizit entziehen und nur +-- das Noetige granten. +revoke all on public.firmen from anon, authenticated; +grant select, update on public.firmen to authenticated; + +-- Feste ID, damit Tests und das Layout (Standard-Logo) die Bestandsfirma kennen. +insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f001', 'Widmann'); + +-- Status und ID einer Firma aendert nur der Service-Client (Plattform-Actions). +create or replace function public.schuetze_firmen_status() +returns trigger +language plpgsql +as $$ +begin + if auth.uid() is not null and (new.aktiv is distinct from old.aktiv or new.id is distinct from old.id) then + raise exception 'Status und ID einer Firma kann nur der Plattform-Betreiber aendern' using errcode = '42501'; + end if; + return new; +end; +$$; + +create trigger schuetze_firmen_status + before update on public.firmen + for each row execute function public.schuetze_firmen_status(); + +-- ---------------------------------------------------------- firmen_smtp +-- Kein Grant, keine Policy: nur der Service-Client kommt heran, das +-- (verschluesselte) Passwort verlaesst die REST-API also nie. +create table public.firmen_smtp ( + firma_id uuid primary key references public.firmen (id) on delete cascade, + host text not null, + port int not null, + secure boolean not null default false, + benutzer text, + passwort_verschluesselt text, + absender_adresse text not null, + absender_name text, + updated_at timestamptz not null default now(), + constraint firmen_smtp_port check (port between 1 and 65535) +); + +alter table public.firmen_smtp enable row level security; +revoke all on public.firmen_smtp from anon, authenticated; + +-- --------------------------------------------------------------- profiles +alter table public.profiles add column firma_id uuid references public.firmen (id); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where role <> 'superadmin'; +alter table public.profiles + add constraint profiles_superadmin_ohne_firma check (role <> 'superadmin' or firma_id is null); +create index profiles_firma_id_idx on public.profiles (firma_id); + +-- Firma des angemeldeten Nutzers, nur wenn die Firma aktiv ist. null = kein +-- Zugriff auf Fachdaten (Superadmin, deaktivierte Firma, nicht zugeordnet). +create or replace function public.user_firma_id() +returns uuid +language sql +stable +security definer +set search_path = public +as $$ + select p.firma_id + from public.profiles p + join public.firmen f on f.id = p.firma_id + where p.id = auth.uid() and f.aktiv; +$$; + +-- ------------------------------------------------- firma_id in Fachtabellen +alter table public.orte add column firma_id uuid references public.firmen (id); +alter table public.fahrzeuge add column firma_id uuid references public.firmen (id); +alter table public.auftraege add column firma_id uuid references public.firmen (id); +alter table public.auftrag_fotos add column firma_id uuid references public.firmen (id); +alter table public.arbeitszeiten add column firma_id uuid references public.firmen (id); +alter table public.nutzer_details add column firma_id uuid references public.firmen (id); +alter table public.notification_outbox add column firma_id uuid references public.firmen (id); +alter table public.auftragsnummer_zaehler add column firma_id uuid references public.firmen (id); + +update public.orte set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.fahrzeuge set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.auftraege set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.auftrag_fotos set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.arbeitszeiten set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.nutzer_details set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.notification_outbox set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.auftragsnummer_zaehler set firma_id = '00000000-0000-0000-0000-00000000f001'; + +alter table public.orte alter column firma_id set not null; +alter table public.fahrzeuge alter column firma_id set not null; +alter table public.auftraege alter column firma_id set not null; +alter table public.auftrag_fotos alter column firma_id set not null; +alter table public.arbeitszeiten alter column firma_id set not null; +alter table public.nutzer_details alter column firma_id set not null; +alter table public.notification_outbox alter column firma_id set not null; +alter table public.auftragsnummer_zaehler alter column firma_id set not null; + +create index orte_firma_id_idx on public.orte (firma_id); +create index fahrzeuge_firma_id_idx on public.fahrzeuge (firma_id); +create index auftraege_firma_id_idx on public.auftraege (firma_id); +create index auftrag_fotos_firma_id_idx on public.auftrag_fotos (firma_id); +create index arbeitszeiten_firma_id_idx on public.arbeitszeiten (firma_id); +create index nutzer_details_firma_id_idx on public.nutzer_details (firma_id); +create index notification_outbox_firma_id_idx on public.notification_outbox (firma_id); + +-- ---------------------------------------------------- Trigger: firma_id setzen +-- Mit Nutzer-Session: immer die eigene Firma (ueberschreibt jeden +-- mitgeschickten Wert). Ohne Session (Service-Client, Migrationen, Tests als +-- postgres): firma_id muss mitgegeben werden. +create or replace function public.firma_aus_sitzung_setzen() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + if auth.uid() is not null then + new.firma_id := public.user_firma_id(); + if new.firma_id is null then + raise exception 'Keine aktive Firma fuer den angemeldeten Nutzer' using errcode = '42501'; + end if; + elsif new.firma_id is null then + raise exception 'firma_id fehlt' using errcode = '23502'; + end if; + return new; +end; +$$; + +create or replace function public.firma_aus_auftrag_setzen() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + if new.auftrag_id is not null then + new.firma_id := (select a.firma_id from public.auftraege a where a.id = new.auftrag_id); + end if; + if new.firma_id is null then + raise exception 'firma_id fehlt' using errcode = '23502'; + end if; + return new; +end; +$$; + +create or replace function public.firma_aus_profil_setzen() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + new.firma_id := (select p.firma_id from public.profiles p where p.id = new.user_id); + if new.firma_id is null then + raise exception 'firma_id fehlt' using errcode = '23502'; + end if; + return new; +end; +$$; + +-- Nur der Erstzuordnung null -> Wert ohne Session (Service-Client nach +-- auth.admin.createUser) ist erlaubt; jede andere Aenderung wirft. +create or replace function public.firma_id_unveraenderlich() +returns trigger +language plpgsql +as $$ +begin + if new.firma_id is distinct from old.firma_id + and not (old.firma_id is null and auth.uid() is null) then + raise exception 'firma_id darf nicht geaendert werden' using errcode = '42501'; + end if; + return new; +end; +$$; + +-- Trigger-Namen mit Praefix a0_/a1_: Postgres feuert gleichartige Trigger +-- alphabetisch, die firma_id muss vor auftragsnummer_generieren stehen. +create trigger a0_firma_setzen before insert on public.orte + for each row execute function public.firma_aus_sitzung_setzen(); +create trigger a0_firma_setzen before insert on public.fahrzeuge + for each row execute function public.firma_aus_sitzung_setzen(); +create trigger a0_firma_setzen before insert on public.auftraege + for each row execute function public.firma_aus_sitzung_setzen(); +create trigger a0_firma_setzen before insert on public.arbeitszeiten + for each row execute function public.firma_aus_sitzung_setzen(); +create trigger a0_firma_setzen before insert on public.auftrag_fotos + for each row execute function public.firma_aus_auftrag_setzen(); +create trigger a0_firma_setzen before insert on public.notification_outbox + for each row execute function public.firma_aus_auftrag_setzen(); +create trigger a0_firma_setzen before insert on public.nutzer_details + for each row execute function public.firma_aus_profil_setzen(); + +create trigger a0_firma_fix before update on public.profiles + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.orte + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.fahrzeuge + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.auftraege + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.arbeitszeiten + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.auftrag_fotos + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.notification_outbox + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.nutzer_details + for each row execute function public.firma_id_unveraenderlich(); + +-- ------------------------------------------- Trigger: firmenfremde Verweise +create or replace function public.auftrag_firma_konsistenz() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + if exists (select 1 from public.orte o + where o.id in (new.abholort_id, new.zielort_id) and o.firma_id <> new.firma_id) + or exists (select 1 from public.fahrzeuge f + where f.id = new.fahrzeug_id and f.firma_id <> new.firma_id) + or exists (select 1 from public.profiles p + where p.id in (new.zugewiesen_an, new.erstellt_von) and p.firma_id is distinct from new.firma_id) + or exists (select 1 from public.auftraege v + where v.id = new.vorgaenger_auftrag_id and v.firma_id <> new.firma_id) then + raise exception 'Firmenfremder Verweis' using errcode = '42501'; + end if; + return new; +end; +$$; + +create trigger a1_firma_konsistenz before insert or update on public.auftraege + for each row execute function public.auftrag_firma_konsistenz(); + +create or replace function public.arbeitszeit_firma_konsistenz() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + if exists (select 1 from public.profiles p + where p.id in (new.fahrer_id, new.korrigiert_von) and p.firma_id is distinct from new.firma_id) then + raise exception 'Firmenfremder Verweis' using errcode = '42501'; + end if; + return new; +end; +$$; + +create trigger a1_firma_konsistenz before insert or update on public.arbeitszeiten + for each row execute function public.arbeitszeit_firma_konsistenz(); + +-- ------------------------------------------------- Eindeutigkeit pro Firma +alter table public.fahrzeuge + drop constraint fahrzeuge_kennzeichen_key, + drop constraint fahrzeuge_fin_key, + add constraint fahrzeuge_firma_kennzeichen_key unique (firma_id, kennzeichen), + add constraint fahrzeuge_firma_fin_key unique (firma_id, fin); + +alter table public.auftraege + drop constraint auftraege_auftragsnummer_key, + add constraint auftraege_firma_auftragsnummer_key unique (firma_id, auftragsnummer); + +alter table public.auftragsnummer_zaehler drop constraint auftragsnummer_zaehler_pkey; +alter table public.auftragsnummer_zaehler add primary key (firma_id, tag); + +create or replace function public.generiere_auftragsnummer() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +declare + naechste int; +begin + if new.auftragsnummer is null or new.auftragsnummer = '' then + insert into public.auftragsnummer_zaehler (firma_id, tag, letzte_nummer) + values (new.firma_id, current_date, 1) + on conflict (firma_id, tag) do update set letzte_nummer = auftragsnummer_zaehler.letzte_nummer + 1 + returning letzte_nummer into naechste; + new.auftragsnummer := to_char(current_date, 'YY-MM-DD') || '-' || lpad(naechste::text, 4, '0'); + end if; + return new; +end; +$$; + +-- ------------------------------------------- FIN-Abgleich nur innerhalb der Firma +create or replace function public.fin_bei_fahrtbeginn(p_auftrag_id uuid, p_fin text) +returns public.app_fin_abgleich +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_fin text := upper(btrim(coalesce(p_fin, ''))); + v_fahrzeug_id uuid; + v_firma_id uuid; + v_hinterlegt text; + v_alt_fin text; + v_alt_status public.app_fin_abgleich; + v_status public.app_fin_abgleich; +begin + if public.user_role() is distinct from 'fahrer'::public.app_role then + raise exception 'Nur Fahrer duerfen den FIN-Abgleich durchfuehren'; + end if; + + if v_fin !~ '^[A-HJ-NPR-Z0-9]{17}$' then + raise exception 'Die FIN muss 17 Zeichen lang sein (A–Z, 0–9, ohne I, O, Q).'; + end if; + + select a.fahrzeug_id, a.firma_id, a.start_fin, a.start_fin_status + into v_fahrzeug_id, v_firma_id, v_alt_fin, v_alt_status + from public.auftraege a + where a.id = p_auftrag_id + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and a.status = 'zugewiesen'::public.app_auftrag_status + for update; + + if not found then + raise exception 'Auftrag nicht gefunden oder nicht im Status zugewiesen'; + end if; + + select f.fin into v_hinterlegt + from public.fahrzeuge f + where f.id = v_fahrzeug_id + for update; + + if v_alt_status = 'abweichend' then + -- Sticky: ein einmal vermerkter Abweichungs-Nachweis wird nicht + -- ueberschrieben (auch nicht durch erneuten Aufruf mit der hinterlegten FIN). + return v_alt_status; + end if; + + if v_alt_status = 'nachgetragen' and v_alt_fin = v_fin then + -- Wiederholter Aufruf mit derselben FIN: Ergebnis bleibt 'nachgetragen'. + v_status := 'nachgetragen'; + elsif v_hinterlegt is null then + if exists (select 1 from public.fahrzeuge f + where f.fin = v_fin and f.id <> v_fahrzeug_id and f.firma_id = v_firma_id) then + v_status := 'abweichend'; + else + begin + update public.fahrzeuge set fin = v_fin where id = v_fahrzeug_id; + v_status := 'nachgetragen'; + exception when unique_violation then + -- Race: parallel wurde dieselbe FIN einem anderen Fahrzeug gegeben. + v_status := 'abweichend'; + end; + end if; + elsif v_hinterlegt = v_fin then + v_status := 'bestaetigt'; + else + v_status := 'abweichend'; + end if; + + perform set_config('app.fin_abgleich', 'an', true); + update public.auftraege + set start_fin = v_fin, start_fin_status = v_status + where id = p_auftrag_id; + perform set_config('app.fin_abgleich', '', true); + + return v_status; +end; +$$; + +-- ------------------------------------- WhatsApp nur bei Firma mit Empfaenger +create or replace function public.auftrag_notification_enqueue() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + insert into public.notification_outbox (event_type, auftrag_id, payload) + select + 'auftrag_erstellt', + new.id, + jsonb_build_object( + 'auftragsnummer', new.auftragsnummer, + 'abholort_adresse', abhol.adresse, + 'zielort_adresse', ziel.adresse, + 'kennzeichen', coalesce(fz.kennzeichen, fz.fin)) + from public.orte abhol + join public.orte ziel on ziel.id = new.zielort_id + join public.fahrzeuge fz on fz.id = new.fahrzeug_id + join public.firmen fi on fi.id = new.firma_id + where abhol.id = new.abholort_id + and fi.whatsapp_empfaenger is not null; + return new; +end; +$$; diff --git a/supabase/migrations/20261012090200_mandanten_rls.sql b/supabase/migrations/20261012090200_mandanten_rls.sql new file mode 100644 index 0000000..3f0fb91 --- /dev/null +++ b/supabase/migrations/20261012090200_mandanten_rls.sql @@ -0,0 +1,418 @@ +-- Mandantenfaehigkeit, Teil 2: jede Policy prueft zusaetzlich die Firma. +-- Rollenlogik unveraendert; der Superadmin hat keine Policy auf Fachdaten. +-- Ausnahme: "Nutzer sehen ihr eigenes Profil" bleibt ohne Firmenbedingung +-- (Login-Pruefung, Layout, Superadmin). + +-- ------------------------------------------------------------------ firmen +create policy "Nutzer sehen die eigene Firma" + on public.firmen for select + using (id = public.user_firma_id()); + +create policy "Admin aktualisiert die eigene Firma" + on public.firmen for update + using (id = public.user_firma_id() and public.user_role() = 'admin') + with check (id = public.user_firma_id() and public.user_role() = 'admin'); + +-- ---------------------------------------------------------------- profiles +drop policy "Admins sehen alle Profile" on public.profiles; +create policy "Admins sehen alle Profile" + on public.profiles for select + using (public.user_role() = 'admin' and firma_id = public.user_firma_id()); + +drop policy "Admins aktualisieren alle Profile" on public.profiles; +create policy "Admins aktualisieren alle Profile" + on public.profiles for update + using (public.user_role() = 'admin' and firma_id = public.user_firma_id()) + with check (public.user_role() = 'admin' and firma_id = public.user_firma_id() and role <> 'superadmin'); + +drop policy "Disponent sieht Fahrer-Profile" on public.profiles; +create policy "Disponent sieht Fahrer-Profile" + on public.profiles for select + using (public.user_role() = 'disponent' and role = 'fahrer' and firma_id = public.user_firma_id()); + +drop policy "Fahrer und Readonly sehen Admin/Disponent-Profile" on public.profiles; +create policy "Fahrer und Readonly sehen Admin/Disponent-Profile" + on public.profiles for select + using ( + public.user_role() in ('fahrer', 'readonly') + and role in ('admin', 'disponent') + and firma_id = public.user_firma_id() + ); + +-- -------------------------------------------------------------------- orte +drop policy "Eingeloggte Nutzer sehen alle Orte" on public.orte; +create policy "Eingeloggte Nutzer sehen alle Orte" + on public.orte for select + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'fahrer', 'readonly')); + +drop policy "Disponent und Admin legen Orte an" on public.orte; +create policy "Disponent und Admin legen Orte an" + on public.orte for insert + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +drop policy "Disponent und Admin bearbeiten Orte" on public.orte; +create policy "Disponent und Admin bearbeiten Orte" + on public.orte for update + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +-- --------------------------------------------------------------- fahrzeuge +drop policy "Eingeloggte Nutzer sehen alle Fahrzeuge" on public.fahrzeuge; +create policy "Eingeloggte Nutzer sehen alle Fahrzeuge" + on public.fahrzeuge for select + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'fahrer', 'readonly')); + +drop policy "Disponent und Admin legen Fahrzeuge an" on public.fahrzeuge; +create policy "Disponent und Admin legen Fahrzeuge an" + on public.fahrzeuge for insert + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +drop policy "Disponent und Admin bearbeiten Fahrzeuge" on public.fahrzeuge; +create policy "Disponent und Admin bearbeiten Fahrzeuge" + on public.fahrzeuge for update + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +-- --------------------------------------------------------------- auftraege +drop policy "Sichtbarkeit von Auftraegen nach Rolle" on public.auftraege; +create policy "Sichtbarkeit von Auftraegen nach Rolle" + on public.auftraege for select + using ( + firma_id = public.user_firma_id() + and ( + public.user_role() in ('admin', 'disponent', 'readonly') + or zugewiesen_an = auth.uid() + or status = 'offen' + ) + ); + +drop policy "Disponent und Admin legen Auftraege an" on public.auftraege; +create policy "Disponent und Admin legen Auftraege an" + on public.auftraege for insert + with check ( + firma_id = public.user_firma_id() + and public.user_role() in ('admin', 'disponent') + and erstellt_von = auth.uid() + ); + +drop policy "Disponent und Admin bearbeiten alle Auftraege" on public.auftraege; +create policy "Disponent und Admin bearbeiten alle Auftraege" + on public.auftraege for update + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +drop policy "Fahrer uebernimmt offene oder bearbeitet eigene Auftraege" on public.auftraege; +create policy "Fahrer uebernimmt offene oder bearbeitet eigene Auftraege" + on public.auftraege for update + using ( + firma_id = public.user_firma_id() + and public.user_role() = 'fahrer' + and (zugewiesen_an = auth.uid() or status = 'offen') + ) + with check ( + firma_id = public.user_firma_id() + and public.user_role() = 'fahrer' + and (zugewiesen_an = auth.uid() or zugewiesen_an is null) + ); + +-- ----------------------------------------------------------- auftrag_fotos +drop policy "Disponent Admin Readonly sehen alle Auftragsfotos" on public.auftrag_fotos; +create policy "Disponent Admin Readonly sehen alle Auftragsfotos" + on public.auftrag_fotos for select + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'readonly')); + +drop policy "Fahrer sieht Fotos des eigenen zugewiesenen Auftrags" on public.auftrag_fotos; +create policy "Fahrer sieht Fotos des eigenen zugewiesenen Auftrags" + on public.auftrag_fotos for select + using ( + firma_id = public.user_firma_id() + and exists ( + select 1 from public.auftraege + where auftraege.id = auftrag_fotos.auftrag_id and auftraege.zugewiesen_an = auth.uid() + ) + ); + +drop policy "Fahrer laedt Fotos fuer eigenen zugewiesenen Auftrag hoch" on public.auftrag_fotos; +create policy "Fahrer laedt Fotos fuer eigenen zugewiesenen Auftrag hoch" + on public.auftrag_fotos for insert + with check ( + firma_id = public.user_firma_id() + and public.user_role() = 'fahrer' + and uploaded_by = auth.uid() + and exists ( + select 1 from public.auftraege + where auftraege.id = auftrag_fotos.auftrag_id + and auftraege.zugewiesen_an = auth.uid() + and ( + (auftrag_fotos.position <> 'schaden' and auftraege.status = 'zugewiesen') + or (auftrag_fotos.position = 'schaden' and auftraege.status in ('zugewiesen', 'unterwegs')) + ) + ) + ); + +drop policy "Admin aktualisiert Auftragsfotos" on public.auftrag_fotos; +create policy "Admin aktualisiert Auftragsfotos" + on public.auftrag_fotos for update + using (firma_id = public.user_firma_id() and public.user_role() = 'admin') + with check (firma_id = public.user_firma_id() and public.user_role() = 'admin'); + +drop policy "Admin loescht Auftragsfotos" on public.auftrag_fotos; +create policy "Admin loescht Auftragsfotos" + on public.auftrag_fotos for delete + using (firma_id = public.user_firma_id() and public.user_role() = 'admin'); + +-- ----------------------------------------------------------- arbeitszeiten +drop policy "Fahrer sieht eigene Arbeitszeiten, Disponent/Admin sehen alle" on public.arbeitszeiten; +create policy "Fahrer sieht eigene Arbeitszeiten, Disponent/Admin sehen alle" + on public.arbeitszeiten for select + using ( + firma_id = public.user_firma_id() + and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) + ); + +drop policy "Fahrer stempelt sich selbst ein" on public.arbeitszeiten; +create policy "Fahrer stempelt sich selbst ein" + on public.arbeitszeiten for insert + with check ( + firma_id = public.user_firma_id() + and public.user_role() = 'fahrer' + and fahrer_id = auth.uid() + and geht_um is null + and korrigiert_von is null + and korrigiert_am is null + ); + +drop policy "Fahrer schliesst Schicht, Disponent/Admin korrigieren" on public.arbeitszeiten; +create policy "Fahrer schliesst Schicht, Disponent/Admin korrigieren" + on public.arbeitszeiten for update + using ( + firma_id = public.user_firma_id() + and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) + ) + with check ( + firma_id = public.user_firma_id() + and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) + ); + +-- ---------------------------------------------------------- nutzer_details +drop policy "Admin und Disponent sehen alle Details" on public.nutzer_details; +create policy "Admin und Disponent sehen alle Details" + on public.nutzer_details for select + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +drop policy "Nutzer und Admin legen Details an" on public.nutzer_details; +create policy "Nutzer und Admin legen Details an" + on public.nutzer_details for insert + with check (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')); + +drop policy "Nutzer und Admin aktualisieren Details" on public.nutzer_details; +create policy "Nutzer und Admin aktualisieren Details" + on public.nutzer_details for update + using (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')) + with check (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')); + +-- "Nutzer sehen ihre eigenen Details" (auth.uid() = user_id) bleibt unveraendert. + +-- ----------------------------------------------------- notification_outbox +drop policy "Admin liest notification_outbox" on public.notification_outbox; +create policy "Admin liest notification_outbox" + on public.notification_outbox for select + using (firma_id = public.user_firma_id() and public.user_role() = 'admin'); + +-- ================================================================ Storage +-- Pfade /...: Zugriff nur, wenn der Auftrag zur eigenen Firma gehoert. + +drop policy "Fahrer liest Fotos des eigenen zugewiesenen Auftrags" on storage.objects; +create policy "Fahrer liest Fotos des eigenen zugewiesenen Auftrags" + on storage.objects for select + using ( + bucket_id = 'auftrag-fotos' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Disponent Admin Readonly lesen alle Auftragsfotos im Storage" on storage.objects; +create policy "Disponent Admin Readonly lesen alle Auftragsfotos im Storage" + on storage.objects for select + using ( + bucket_id = 'auftrag-fotos' + and public.user_role() in ('admin', 'disponent', 'readonly') + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Fahrer laedt Auftragsfotos hoch" on storage.objects; +create policy "Fahrer laedt Auftragsfotos hoch" + on storage.objects for insert + with check ( + bucket_id = 'auftrag-fotos' + and public.user_role() = 'fahrer' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and ( + (split_part(name, '/', 2) not like 'schaden-%' and a.status = 'zugewiesen') + or (split_part(name, '/', 2) like 'schaden-%' and a.status in ('zugewiesen', 'unterwegs')) + ) + ) + ); + +drop policy "Admin aktualisiert Auftragsfotos im Storage" on storage.objects; +create policy "Admin aktualisiert Auftragsfotos im Storage" + on storage.objects for update + using ( + bucket_id = 'auftrag-fotos' + and public.user_role() = 'admin' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Admin loescht Auftragsfotos im Storage" on storage.objects; +create policy "Admin loescht Auftragsfotos im Storage" + on storage.objects for delete + using ( + bucket_id = 'auftrag-fotos' + and public.user_role() = 'admin' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Fahrer liest Unterschrift des eigenen zugewiesenen Auftrags" on storage.objects; +create policy "Fahrer liest Unterschrift des eigenen zugewiesenen Auftrags" + on storage.objects for select + using ( + bucket_id = 'auftrag-unterschriften' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Disponent Admin Readonly lesen alle Unterschriften im Storage" on storage.objects; +create policy "Disponent Admin Readonly lesen alle Unterschriften im Storage" + on storage.objects for select + using ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() in ('admin', 'disponent', 'readonly') + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Fahrer laedt Unterschrift bei Fahrtende hoch" on storage.objects; +create policy "Fahrer laedt Unterschrift bei Fahrtende hoch" + on storage.objects for insert + with check ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'fahrer' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and a.status = 'unterwegs' + ) + ); + +drop policy "Fahrer aktualisiert eigene Unterschrift bei Fahrtende" on storage.objects; +create policy "Fahrer aktualisiert eigene Unterschrift bei Fahrtende" + on storage.objects for update + using ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'fahrer' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and a.status = 'unterwegs' + ) + ) + with check ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'fahrer' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and a.status = 'unterwegs' + ) + ); + +drop policy "Admin aktualisiert Unterschriften im Storage" on storage.objects; +create policy "Admin aktualisiert Unterschriften im Storage" + on storage.objects for update + using ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'admin' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Admin loescht Unterschriften im Storage" on storage.objects; +create policy "Admin loescht Unterschriften im Storage" + on storage.objects for delete + using ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'admin' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +-- ------------------------------------------------------------ firmen-logos +insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types) +values ('firmen-logos', 'firmen-logos', false, 1048576, array['image/png', 'image/jpeg', 'image/svg+xml']) +on conflict (id) do nothing; + +create policy "Nutzer lesen das Logo der eigenen Firma" + on storage.objects for select + using (bucket_id = 'firmen-logos' and (storage.foldername(name))[1] = public.user_firma_id()::text); + +create policy "Admin laedt das Logo der eigenen Firma hoch" + on storage.objects for insert + with check ( + bucket_id = 'firmen-logos' + and public.user_role() = 'admin' + and (storage.foldername(name))[1] = public.user_firma_id()::text + ); + +create policy "Admin aktualisiert das Logo der eigenen Firma" + on storage.objects for update + using ( + bucket_id = 'firmen-logos' + and public.user_role() = 'admin' + and (storage.foldername(name))[1] = public.user_firma_id()::text + ) + with check ( + bucket_id = 'firmen-logos' + and public.user_role() = 'admin' + and (storage.foldername(name))[1] = public.user_firma_id()::text + ); + +create policy "Admin loescht das Logo der eigenen Firma" + on storage.objects for delete + using ( + bucket_id = 'firmen-logos' + and public.user_role() = 'admin' + and (storage.foldername(name))[1] = public.user_firma_id()::text + ); diff --git a/supabase/migrations/20261012090300_firmen_logo_pfad.sql b/supabase/migrations/20261012090300_firmen_logo_pfad.sql new file mode 100644 index 0000000..9180596 --- /dev/null +++ b/supabase/migrations/20261012090300_firmen_logo_pfad.sql @@ -0,0 +1,6 @@ +-- Das Logo muss im Ordner der eigenen Firma liegen: der PDF-Versand laedt es +-- mit dem Service-Client, ein fremder Pfad wuerde das Logo einer anderen +-- Firma ins eigene Protokoll holen. +alter table public.firmen + add constraint firmen_logo_pfad_eigener_ordner + check (logo_pfad is null or logo_pfad like id::text || '/%'); diff --git a/supabase/migrations/20261012090400_firmen_logo_pfad_regex.sql b/supabase/migrations/20261012090400_firmen_logo_pfad_regex.sql new file mode 100644 index 0000000..590fb90 --- /dev/null +++ b/supabase/migrations/20261012090400_firmen_logo_pfad_regex.sql @@ -0,0 +1,8 @@ +-- Der LIKE-Check aus 20261012090300 liess "/..//logo-1.png" zu. +-- Der Pfad muss exakt dem Muster aus logoPfad() (web/lib/firma/logo.ts) entsprechen. +alter table public.firmen + drop constraint firmen_logo_pfad_eigener_ordner; + +alter table public.firmen + add constraint firmen_logo_pfad_eigener_ordner + check (logo_pfad is null or logo_pfad ~ ('^' || id::text || '/logo-[0-9]+\.(png|jpg|svg)$')); diff --git a/supabase/tests/arbeitszeiten_rls_test.sql b/supabase/tests/arbeitszeiten_rls_test.sql index caa2e11..7a79cdc 100644 --- a/supabase/tests/arbeitszeiten_rls_test.sql +++ b/supabase/tests/arbeitszeiten_rls_test.sql @@ -8,6 +8,7 @@ insert into auth.users (id, email) values ('aa444444-4444-4444-4444-444444444444', 'fahrer-zwei@arbeitszeiten.test.local'), ('aa555555-5555-5555-5555-555555555555', 'readonly@arbeitszeiten.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'aa111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'aa222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = 'aa333333-3333-3333-3333-333333333333'; @@ -74,8 +75,8 @@ select throws_ok( reset role; -insert into public.arbeitszeiten (id, fahrer_id, kommt_um) values - ('b2222222-2222-2222-2222-222222222222', 'aa444444-4444-4444-4444-444444444444', '2026-07-13 07:00:00+00'); +insert into public.arbeitszeiten (id, fahrer_id, kommt_um, firma_id) values + ('b2222222-2222-2222-2222-222222222222', 'aa444444-4444-4444-4444-444444444444', '2026-07-13 07:00:00+00', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "aa333333-3333-3333-3333-333333333333", "role": "authenticated"}'; diff --git a/supabase/tests/auftraege_rls_test.sql b/supabase/tests/auftraege_rls_test.sql index 2a01208..7674a46 100644 --- a/supabase/tests/auftraege_rls_test.sql +++ b/supabase/tests/auftraege_rls_test.sql @@ -8,6 +8,7 @@ insert into auth.users (id, email) values ('f4444444-4444-4444-4444-444444444444', 'fahrer-zwei@auftraege.test.local'), ('05555555-5555-5555-5555-555555555555', 'readonly@auftraege.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'd2222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = 'f3333333-3333-3333-3333-333333333333'; @@ -15,13 +16,13 @@ update public.profiles set role = 'fahrer' where id = 'f4444444-4444-4444-4444-4 -- readonly bleibt auf dem Trigger-Default 'readonly' (siehe Fundament, -- handle_new_user()), kein explizites update noetig. -insert into public.orte (id, adresse, ansprechpartner) values - ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('f0000000-0000-0000-0000-000000000001', 'M-AB 123'), - ('f0000000-0000-0000-0000-000000000002', 'M-CD 456'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001'), + ('f0000000-0000-0000-0000-000000000002', 'M-CD 456', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "d2222222-2222-2222-2222-222222222222", "role": "authenticated"}'; diff --git a/supabase/tests/auftrag_fotos_rls_test.sql b/supabase/tests/auftrag_fotos_rls_test.sql index 2ca0d78..206d6d5 100644 --- a/supabase/tests/auftrag_fotos_rls_test.sql +++ b/supabase/tests/auftrag_fotos_rls_test.sql @@ -7,23 +7,24 @@ insert into auth.users (id, email) values ('ff333333-3333-3333-3333-333333333333', 'fahrer-eins-fotos@auftraege.test.local'), ('ff444444-4444-4444-4444-444444444444', 'fahrer-zwei-fotos@auftraege.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'aa111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'dd222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = 'ff333333-3333-3333-3333-333333333333'; update public.profiles set role = 'fahrer' where id = 'ff444444-4444-4444-4444-444444444444'; -insert into public.orte (id, adresse, ansprechpartner) values - ('20111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('20222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('20111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('20222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('20333333-0000-0000-0000-000000000001', 'M-EF 789'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('20333333-0000-0000-0000-000000000001', 'M-EF 789', '00000000-0000-0000-0000-00000000f001'); -- Auftrag A: dem Fahrer "eins" zugewiesen, status = 'zugewiesen' -- fuer die -- "eigener, noch nicht gestarteter Auftrag"-Faelle (Pflichtfoto UND -- Schadensfoto duerfen hier hochgeladen werden). insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '20000000-0000-0000-0000-000000000001', '20111111-1111-1111-1111-111111111111', @@ -32,13 +33,14 @@ insert into public.auftraege ( 'dd222222-2222-2222-2222-222222222222', 'zugewiesen', 'ff333333-3333-3333-3333-333333333333', - 1000 + 1000, + '00000000-0000-0000-0000-00000000f001' ); -- Auftrag B: dem Fahrer "zwei" zugewiesen -- aus Sicht von Fahrer "eins" ein -- fremder Auftrag, fuer die SELECT- und INSERT-RLS-Blockade-Faelle. insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '20000000-0000-0000-0000-000000000002', '20111111-1111-1111-1111-111111111111', @@ -47,7 +49,8 @@ insert into public.auftraege ( 'dd222222-2222-2222-2222-222222222222', 'zugewiesen', 'ff444444-4444-4444-4444-444444444444', - 500 + 500, + '00000000-0000-0000-0000-00000000f001' ); -- Auftrag C: dem Fahrer "eins" zugewiesen, aber direkt mit status = @@ -58,7 +61,7 @@ insert into public.auftraege ( -- unabhaengig von auftraege_rls_test.sql und fokussiert sie ausschliesslich -- auf die auftrag_fotos/storage.objects-Policies statt auf den Trigger. insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '20000000-0000-0000-0000-000000000003', '20111111-1111-1111-1111-111111111111', @@ -67,7 +70,8 @@ insert into public.auftraege ( 'dd222222-2222-2222-2222-222222222222', 'unterwegs', 'ff333333-3333-3333-3333-333333333333', - 2000 + 2000, + '00000000-0000-0000-0000-00000000f001' ); -- Ein Foto + ein Storage-Objekt fuer Auftrag B, als postgres (RLS-frei) diff --git a/supabase/tests/auftrag_unterschrift_rls_test.sql b/supabase/tests/auftrag_unterschrift_rls_test.sql index 96dcfa1..7052e92 100644 --- a/supabase/tests/auftrag_unterschrift_rls_test.sql +++ b/supabase/tests/auftrag_unterschrift_rls_test.sql @@ -6,20 +6,21 @@ insert into auth.users (id, email) values ('ff666666-6666-6666-6666-666666666666', 'fahrer-eins-unterschrift@auftraege.test.local'), ('ff777777-7777-7777-7777-777777777777', 'fahrer-zwei-unterschrift@auftraege.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'aa555555-5555-5555-5555-555555555555'; update public.profiles set role = 'fahrer' where id = 'ff666666-6666-6666-6666-666666666666'; update public.profiles set role = 'fahrer' where id = 'ff777777-7777-7777-7777-777777777777'; -insert into public.orte (id, adresse, ansprechpartner) values - ('21111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('21222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('21111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('21222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('21333333-0000-0000-0000-000000000001', 'M-UN 001'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('21333333-0000-0000-0000-000000000001', 'M-UN 001', '00000000-0000-0000-0000-00000000f001'); -- Auftrag A: Fahrer "eins", status 'unterwegs' -- Upload muss hier gelingen. insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '21000000-0000-0000-0000-000000000001', '21111111-1111-1111-1111-111111111111', @@ -28,13 +29,14 @@ insert into public.auftraege ( 'aa555555-5555-5555-5555-555555555555', 'unterwegs', 'ff666666-6666-6666-6666-666666666666', - 1000 + 1000, + '00000000-0000-0000-0000-00000000f001' ); -- Auftrag B: Fahrer "eins", status 'zugewiesen' -- Upload muss hier verboten -- bleiben (Unterschrift ist nur bei Fahrtende/status='unterwegs' erlaubt). insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '21000000-0000-0000-0000-000000000002', '21111111-1111-1111-1111-111111111111', @@ -43,13 +45,14 @@ insert into public.auftraege ( 'aa555555-5555-5555-5555-555555555555', 'zugewiesen', 'ff666666-6666-6666-6666-666666666666', - 1000 + 1000, + '00000000-0000-0000-0000-00000000f001' ); -- Auftrag C: Fahrer "zwei", status 'unterwegs' -- aus Sicht von Fahrer -- "eins" ein fremder Auftrag. insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '21000000-0000-0000-0000-000000000003', '21111111-1111-1111-1111-111111111111', @@ -58,7 +61,8 @@ insert into public.auftraege ( 'aa555555-5555-5555-5555-555555555555', 'unterwegs', 'ff777777-7777-7777-7777-777777777777', - 500 + 500, + '00000000-0000-0000-0000-00000000f001' ); insert into storage.buckets (id, name, public) values ('auftrag-unterschriften', 'auftrag-unterschriften', false) diff --git a/supabase/tests/auftragsnummer_test.sql b/supabase/tests/auftragsnummer_test.sql index 0177726..4397aca 100644 --- a/supabase/tests/auftragsnummer_test.sql +++ b/supabase/tests/auftragsnummer_test.sql @@ -3,14 +3,15 @@ select plan(5); insert into auth.users (id, email) values ('a1111111-1111-1111-1111-111111111111', 'admin@auftragsnummer.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111'; -insert into public.orte (id, adresse, ansprechpartner) values - ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('f0000000-0000-0000-0000-000000000001', 'M-AB 123'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "a1111111-1111-1111-1111-111111111111", "role": "authenticated"}'; @@ -55,7 +56,7 @@ select throws_ok( ('30000000-0000-0000-0000-000000000004', '01111111-1111-1111-1111-111111111111', '02222222-2222-2222-2222-222222222222', 'f0000000-0000-0000-0000-000000000001', 'a1111111-1111-1111-1111-111111111111', 'MEINE-EIGENE-NUMMER') $$, '23505', - 'duplicate key value violates unique constraint "auftraege_auftragsnummer_key"', + 'duplicate key value violates unique constraint "auftraege_firma_auftragsnummer_key"', 'Doppelte, manuell eingegebene Auftragsnummer wird durch den Unique-Constraint abgelehnt' ); diff --git a/supabase/tests/fahrzeug_fin_test.sql b/supabase/tests/fahrzeug_fin_test.sql index f6f9909..2843a3b 100644 --- a/supabase/tests/fahrzeug_fin_test.sql +++ b/supabase/tests/fahrzeug_fin_test.sql @@ -8,27 +8,29 @@ insert into auth.users (id, email) values ('f1a00000-0000-0000-0000-000000000004', 'fahrer-zwei-fin@test.local'), ('f1a00000-0000-0000-0000-000000000005', 'readonly-fin@test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; +update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; update public.profiles set role = 'admin' where id = 'f1a00000-0000-0000-0000-000000000001'; update public.profiles set role = 'disponent' where id = 'f1a00000-0000-0000-0000-000000000002'; update public.profiles set role = 'fahrer' where id = 'f1a00000-0000-0000-0000-000000000003'; update public.profiles set role = 'fahrer' where id = 'f1a00000-0000-0000-0000-000000000004'; -- readonly bleibt auf dem Trigger-Default. -insert into public.orte (id, adresse, ansprechpartner) values - ('f1b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('f1b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('f1b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('f1b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -- F1: nur Kennzeichen (FIN wird nachgetragen) -- F2: FIN A hinterlegt -- F3: nur Kennzeichen (Fahrer gibt FIN von F2 ein) -insert into public.fahrzeuge (id, kennzeichen, fin) values - ('f1c00000-0000-0000-0000-000000000001', 'M-FN 001', null), - ('f1c00000-0000-0000-0000-000000000002', 'M-FN 002', 'WDB9066331S123456'), - ('f1c00000-0000-0000-0000-000000000003', 'M-FN 003', null); +insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values + ('f1c00000-0000-0000-0000-000000000001', 'M-FN 001', null, '00000000-0000-0000-0000-00000000f001'), + ('f1c00000-0000-0000-0000-000000000002', 'M-FN 002', 'WDB9066331S123456', '00000000-0000-0000-0000-00000000f001'), + ('f1c00000-0000-0000-0000-000000000003', 'M-FN 003', null, '00000000-0000-0000-0000-00000000f001'); -- 1) Format-Check select throws_ok( - $$ insert into public.fahrzeuge (kennzeichen, fin) values ('M-FN 010', 'WDB906633IS12345X') $$, + $$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values ('M-FN 010', 'WDB906633IS12345X', '00000000-0000-0000-0000-00000000f001') $$, '23514', null, 'FIN mit I wird vom Format-Check abgelehnt' @@ -36,7 +38,7 @@ select throws_ok( -- 2) Kennzeichen oder FIN select throws_ok( - $$ insert into public.fahrzeuge (kennzeichen, fin) values (null, null) $$, + $$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values (null, null, '00000000-0000-0000-0000-00000000f001') $$, '23514', null, 'Fahrzeug ohne Kennzeichen und ohne FIN wird abgelehnt' @@ -44,27 +46,27 @@ select throws_ok( -- 3) Nur FIN ist erlaubt select lives_ok( - $$ insert into public.fahrzeuge (id, kennzeichen, fin) values ('f1c00000-0000-0000-0000-000000000004', null, 'VF1RFB00X12345678') $$, + $$ insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values ('f1c00000-0000-0000-0000-000000000004', null, 'VF1RFB00X12345678', '00000000-0000-0000-0000-00000000f001') $$, 'Fahrzeug nur mit FIN kann angelegt werden' ); -- 4) FIN eindeutig select throws_ok( - $$ insert into public.fahrzeuge (kennzeichen, fin) values ('M-FN 011', 'WDB9066331S123456') $$, + $$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values ('M-FN 011', 'WDB9066331S123456', '00000000-0000-0000-0000-00000000f001') $$, '23505', null, 'Doppelte FIN wird abgelehnt' ); -- Auftraege (als postgres angelegt) -insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km) values - ('f1d00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000001', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null), - ('f1d00000-0000-0000-0000-000000000002', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null), - ('f1d00000-0000-0000-0000-000000000003', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null), - ('f1d00000-0000-0000-0000-000000000004', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000003', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null), - ('f1d00000-0000-0000-0000-000000000005', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000004', null), - ('f1d00000-0000-0000-0000-000000000006', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'unterwegs', 'f1a00000-0000-0000-0000-000000000003', 1000), - ('f1d00000-0000-0000-0000-000000000007', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000004', 'f1a00000-0000-0000-0000-000000000001', 'offen', null, null); +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id) values + ('f1d00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000001', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000002', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000003', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000004', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000003', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000005', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000004', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000006', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'unterwegs', 'f1a00000-0000-0000-0000-000000000003', 1000, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000007', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000004', 'f1a00000-0000-0000-0000-000000000001', 'offen', null, null, '00000000-0000-0000-0000-00000000f001'); -- 5) Outbox: Fahrzeug ohne Kennzeichen -> FIN im Payload select is( diff --git a/supabase/tests/firmen_logo_pfad_test.sql b/supabase/tests/firmen_logo_pfad_test.sql new file mode 100644 index 0000000..d98ac91 --- /dev/null +++ b/supabase/tests/firmen_logo_pfad_test.sql @@ -0,0 +1,34 @@ +begin; +select plan(4); + +insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); + +select throws_ok( + $$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f001/logo-1.png' + where id = '00000000-0000-0000-0000-00000000f002' $$, + '23514', null, + 'Logo-Pfad im Ordner einer fremden Firma wird abgelehnt' +); + +select throws_ok( + $$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/../00000000-0000-0000-0000-00000000f001/logo-1.png' + where id = '00000000-0000-0000-0000-00000000f002' $$, + '23514', null, + 'Pfad mit ../ in den Ordner einer fremden Firma wird abgelehnt' +); + +select throws_ok( + $$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/x.png' + where id = '00000000-0000-0000-0000-00000000f002' $$, + '23514', null, + 'Pfad im eigenen Ordner, aber nicht im Format logo-., wird abgelehnt' +); + +select lives_ok( + $$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/logo-1.png' + where id = '00000000-0000-0000-0000-00000000f002' $$, + 'Logo-Pfad im eigenen Firmenordner ist erlaubt' +); + +select * from finish(); +rollback; diff --git a/supabase/tests/mandanten_rls_test.sql b/supabase/tests/mandanten_rls_test.sql new file mode 100644 index 0000000..8fb3a85 --- /dev/null +++ b/supabase/tests/mandanten_rls_test.sql @@ -0,0 +1,147 @@ +begin; +select plan(30); + +insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); + +insert into auth.users (id, email) values + ('a0000000-0000-0000-0000-0000000000a1', 'admin-a@rls.test.local'), + ('a0000000-0000-0000-0000-0000000000a2', 'dispo-a@rls.test.local'), + ('a0000000-0000-0000-0000-0000000000a3', 'fahrer-a@rls.test.local'), + ('b0000000-0000-0000-0000-0000000000b1', 'admin-b@rls.test.local'), + ('b0000000-0000-0000-0000-0000000000b2', 'dispo-b@rls.test.local'), + ('b0000000-0000-0000-0000-0000000000b3', 'fahrer-b@rls.test.local'), + ('5a000000-0000-0000-0000-000000000001', 'superadmin@rls.test.local'); + +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'admin' where id = 'a0000000-0000-0000-0000-0000000000a1'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'disponent' where id = 'a0000000-0000-0000-0000-0000000000a2'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'fahrer' where id = 'a0000000-0000-0000-0000-0000000000a3'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'admin' where id = 'b0000000-0000-0000-0000-0000000000b1'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'disponent' where id = 'b0000000-0000-0000-0000-0000000000b2'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'fahrer' where id = 'b0000000-0000-0000-0000-0000000000b3'; +update public.profiles set role = 'superadmin' where id = '5a000000-0000-0000-0000-000000000001'; + +update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; + +-- Daten Firma A +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('a0000000-0000-0000-0000-0000000000c1', 'Ort A', 'Herr A', '00000000-0000-0000-0000-00000000f001'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('a0000000-0000-0000-0000-0000000000d1', 'MT-A 1', '00000000-0000-0000-0000-00000000f001'); +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, firma_id) values + ('a0000000-0000-0000-0000-0000000000e1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', + 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', 'zugewiesen', + 'a0000000-0000-0000-0000-0000000000a3', '00000000-0000-0000-0000-00000000f001'), + ('a0000000-0000-0000-0000-0000000000e2', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', + 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', 'offen', null, + '00000000-0000-0000-0000-00000000f001'); +insert into public.auftrag_fotos (auftrag_id, position, storage_path, uploaded_by) values + ('a0000000-0000-0000-0000-0000000000e1', 'front', 'a0000000-0000-0000-0000-0000000000e1/front.jpg', 'a0000000-0000-0000-0000-0000000000a3'); +insert into public.arbeitszeiten (fahrer_id, kommt_um, firma_id) values + ('a0000000-0000-0000-0000-0000000000a3', now(), '00000000-0000-0000-0000-00000000f001'); +insert into public.nutzer_details (user_id, telefon) values + ('a0000000-0000-0000-0000-0000000000a3', '+4915100000002'); +insert into storage.objects (bucket_id, name, owner) values + ('auftrag-fotos', 'a0000000-0000-0000-0000-0000000000e1/front.jpg', 'a0000000-0000-0000-0000-0000000000a3'), + ('auftrag-unterschriften', 'a0000000-0000-0000-0000-0000000000e1/unterschrift.png', 'a0000000-0000-0000-0000-0000000000a3'), + ('firmen-logos', '00000000-0000-0000-0000-00000000f001/logo-1.png', 'a0000000-0000-0000-0000-0000000000a1'); + +-- Daten Firma B +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('b0000000-0000-0000-0000-0000000000c1', 'Ort B', 'Frau B', '00000000-0000-0000-0000-00000000f002'); + +-- ====================== Admin B +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; + +select ok(not exists (select 1 from public.orte where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Orte von A'); +select ok(exists (select 1 from public.orte where id = 'b0000000-0000-0000-0000-0000000000c1'), 'Admin B sieht eigene Orte'); +select ok(not exists (select 1 from public.fahrzeuge where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Fahrzeuge von A'); +select ok(not exists (select 1 from public.auftraege where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Auftraege von A'); +select ok(not exists (select 1 from public.auftrag_fotos), 'Admin B sieht keine Auftragsfotos von A'); +select ok(not exists (select 1 from public.arbeitszeiten), 'Admin B sieht keine Arbeitszeiten von A'); +select ok(not exists (select 1 from public.nutzer_details), 'Admin B sieht keine Nutzer-Details von A'); +select ok(not exists (select 1 from public.profiles where firma_id = '00000000-0000-0000-0000-00000000f001'), 'Admin B sieht keine Profile von A'); +select ok(not exists (select 1 from public.notification_outbox), 'Admin B sieht keine Outbox-Zeilen von A'); +select is((select array_agg(id) from public.firmen), array['00000000-0000-0000-0000-00000000f002'::uuid], 'Admin B sieht nur die eigene Firma'); +select ok(not exists (select 1 from storage.objects where name like 'a0000000-0000-0000-0000-0000000000e1/%' or name like '00000000-0000-0000-0000-00000000f001/%'), 'Admin B sieht keine Storage-Objekte von A'); + +select is_empty( + $$ update public.orte set adresse = 'x' where id = 'a0000000-0000-0000-0000-0000000000c1' returning 1 $$, + 'Admin B kann keinen Ort von A aendern'); +select is_empty( + $$ update public.auftraege set status = 'storniert' where id = 'a0000000-0000-0000-0000-0000000000e2' returning 1 $$, + 'Admin B kann keinen Auftrag von A aendern'); +select is_empty( + $$ update public.profiles set name = 'x' where id = 'a0000000-0000-0000-0000-0000000000a3' returning 1 $$, + 'Admin B kann kein Profil von A aendern'); +select is_empty( + $$ update public.firmen set name = 'x' where id = '00000000-0000-0000-0000-00000000f001' returning 1 $$, + 'Admin B kann Firma A nicht umbenennen'); +select isnt_empty( + $$ update public.firmen set name = 'Firma B neu' where id = '00000000-0000-0000-0000-00000000f002' returning 1 $$, + 'Admin B kann die eigene Firma umbenennen'); + +select throws_ok( + $$ update public.profiles set role = 'superadmin' where id = 'b0000000-0000-0000-0000-0000000000b3' $$, + null, null, + 'Admin B kann niemanden zum Superadmin machen'); +select throws_ok( + $$ insert into public.nutzer_details (user_id, telefon) values ('a0000000-0000-0000-0000-0000000000a1', '+4915100000003') $$, + '42501', 'new row violates row-level security policy for table "nutzer_details"', + 'Admin B kann keine Details fuer Nutzer von A anlegen'); +select throws_ok( + $$ insert into storage.objects (bucket_id, name, owner) values ('firmen-logos', '00000000-0000-0000-0000-00000000f001/logo-2.png', 'b0000000-0000-0000-0000-0000000000b1') $$, + '42501', 'new row violates row-level security policy for table "objects"', + 'Admin B kann kein Logo fuer Firma A hochladen'); +select lives_ok( + $$ insert into storage.objects (bucket_id, name, owner) values ('firmen-logos', '00000000-0000-0000-0000-00000000f002/logo-1.png', 'b0000000-0000-0000-0000-0000000000b1') $$, + 'Admin B kann ein Logo fuer die eigene Firma hochladen'); +select throws_ok( + $$ select * from public.firmen_smtp $$, + '42501', null, + 'firmen_smtp ist fuer angemeldete Nutzer gesperrt'); + +reset role; +reset request.jwt.claims; + +-- ====================== Fahrer B +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b3", "role": "authenticated"}'; +select ok(not exists (select 1 from public.auftraege where id = 'a0000000-0000-0000-0000-0000000000e2'), 'Fahrer B sieht den offenen Auftrag von A nicht'); +select is_empty( + $$ update public.auftraege set zugewiesen_an = 'b0000000-0000-0000-0000-0000000000b3', status = 'zugewiesen' where id = 'a0000000-0000-0000-0000-0000000000e2' returning 1 $$, + 'Fahrer B kann den offenen Auftrag von A nicht uebernehmen'); +reset role; +reset request.jwt.claims; + +-- ====================== Disponent A +set local role authenticated; +set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a2", "role": "authenticated"}'; +select ok( + exists (select 1 from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a3') + and not exists (select 1 from public.profiles where id = 'b0000000-0000-0000-0000-0000000000b3'), + 'Disponent A sieht nur Fahrer der eigenen Firma'); +select ok(exists (select 1 from public.auftraege where id = 'a0000000-0000-0000-0000-0000000000e1'), 'Disponent A sieht eigene Auftraege'); +reset role; +reset request.jwt.claims; + +-- ====================== Superadmin +set local role authenticated; +set local request.jwt.claims to '{"sub": "5a000000-0000-0000-0000-000000000001", "role": "authenticated"}'; +select ok(not exists (select 1 from public.auftraege), 'Superadmin sieht keine Auftraege'); +select ok(not exists (select 1 from public.firmen), 'Superadmin sieht ueber RLS keine Firmen'); +select ok(exists (select 1 from public.profiles where id = '5a000000-0000-0000-0000-000000000001'), 'Superadmin sieht sein eigenes Profil'); +reset role; +reset request.jwt.claims; + +-- ====================== Firma A deaktiviert +update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f001'; +set local role authenticated; +set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a1", "role": "authenticated"}'; +select ok(not exists (select 1 from public.auftraege), 'Deaktivierte Firma: Admin sieht keine Auftraege mehr'); +select ok(exists (select 1 from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a1'), 'Deaktivierte Firma: eigenes Profil bleibt lesbar'); +reset role; +reset request.jwt.claims; + +select * from finish(); +rollback; diff --git a/supabase/tests/mandanten_struktur_test.sql b/supabase/tests/mandanten_struktur_test.sql new file mode 100644 index 0000000..c9b03a1 --- /dev/null +++ b/supabase/tests/mandanten_struktur_test.sql @@ -0,0 +1,223 @@ +begin; +select plan(20); + +-- Firma B neben der Bestandsfirma Widmann (f001) +insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); + +insert into auth.users (id, email) values + ('a0000000-0000-0000-0000-0000000000a1', 'admin-a@mandant.test.local'), + ('a0000000-0000-0000-0000-0000000000a3', 'fahrer-a@mandant.test.local'), + ('b0000000-0000-0000-0000-0000000000b1', 'admin-b@mandant.test.local'), + ('b0000000-0000-0000-0000-0000000000b3', 'fahrer-b@mandant.test.local'), + ('5a000000-0000-0000-0000-000000000001', 'superadmin@mandant.test.local'); + +-- 1) Neues Profil hat keine Firma (handle_new_user bleibt unveraendert) +select is( + (select firma_id from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a1'), + null::uuid, + 'Neues Profil startet ohne Firma' +); + +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'admin' + where id = 'a0000000-0000-0000-0000-0000000000a1'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'fahrer' + where id = 'a0000000-0000-0000-0000-0000000000a3'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'admin' + where id = 'b0000000-0000-0000-0000-0000000000b1'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'fahrer' + where id = 'b0000000-0000-0000-0000-0000000000b3'; +update public.profiles set role = 'superadmin' where id = '5a000000-0000-0000-0000-000000000001'; + +-- 2) Superadmin mit Firma ist verboten +select throws_ok( + $$ update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' + where id = '5a000000-0000-0000-0000-000000000001' $$, + '23514', null, + 'Superadmin darf keiner Firma angehoeren' +); + +-- 3) Firmenwechsel eines Profils ist verboten (auch ohne Session, wenn schon gesetzt) +select throws_ok( + $$ update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002' + where id = 'a0000000-0000-0000-0000-0000000000a3' $$, + '42501', 'firma_id darf nicht geaendert werden', + 'firma_id eines Profils ist unveraenderlich' +); + +-- Stammdaten ohne Session: firma_id explizit +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('a0000000-0000-0000-0000-0000000000c1', 'Ort A', 'Herr A', '00000000-0000-0000-0000-00000000f001'), + ('b0000000-0000-0000-0000-0000000000c1', 'Ort B', 'Frau B', '00000000-0000-0000-0000-00000000f002'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('a0000000-0000-0000-0000-0000000000d1', 'MT-AB 1', '00000000-0000-0000-0000-00000000f001'); + +-- 4) Ohne Session und ohne firma_id: Fehler +select throws_ok( + $$ insert into public.orte (adresse, ansprechpartner) values ('X', 'Y') $$, + '23502', 'firma_id fehlt', + 'Insert ohne Session braucht eine firma_id' +); + +-- 5) Gleiches Kennzeichen in zwei Firmen ist erlaubt +select lives_ok( + $$ insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('b0000000-0000-0000-0000-0000000000d1', 'MT-AB 1', '00000000-0000-0000-0000-00000000f002') $$, + 'Gleiches Kennzeichen in einer anderen Firma ist erlaubt' +); + +-- 6) Doppeltes Kennzeichen in derselben Firma nicht +select throws_ok( + $$ insert into public.fahrzeuge (kennzeichen, firma_id) values ('MT-AB 1', '00000000-0000-0000-0000-00000000f001') $$, + '23505', null, + 'Doppeltes Kennzeichen in derselben Firma scheitert' +); + +-- Session als Admin B +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; + +-- 7) Mitgeschickte fremde firma_id wird ueberschrieben +select is( + (select public.user_firma_id()), + '00000000-0000-0000-0000-00000000f002'::uuid, + 'user_firma_id liefert die Firma des angemeldeten Nutzers' +); + +reset role; +reset request.jwt.claims; + +-- Insert mit Session, Rueckgabe ueber eine Hilfstabelle (RLS-Policies sind in Task 1 noch rollenbasiert) +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; +insert into public.orte (id, adresse, ansprechpartner, firma_id) + values ('b0000000-0000-0000-0000-0000000000c2', 'Ort B2', 'Herr B2', '00000000-0000-0000-0000-00000000f001'); +reset role; +reset request.jwt.claims; + +select is( + (select firma_id from public.orte where id = 'b0000000-0000-0000-0000-0000000000c2'), + '00000000-0000-0000-0000-00000000f002'::uuid, + 'Mitgeschickte fremde firma_id wird durch die eigene Firma ersetzt' +); + +-- 9) Auftrag mit Ort einer fremden Firma: Exception +select throws_ok( + $$ insert into public.auftraege (abholort_id, zielort_id, fahrzeug_id, erstellt_von, firma_id) values + ('a0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', + 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', + '00000000-0000-0000-0000-00000000f002') $$, + '42501', 'Firmenfremder Verweis', + 'Auftrag mit Ort einer fremden Firma scheitert' +); + +-- 10) Auftrag mit Fahrer einer fremden Firma: Exception +select throws_ok( + $$ insert into public.auftraege (abholort_id, zielort_id, fahrzeug_id, erstellt_von, zugewiesen_an, status, firma_id) values + ('b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', + 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', + 'a0000000-0000-0000-0000-0000000000a3', 'zugewiesen', '00000000-0000-0000-0000-00000000f002') $$, + '42501', 'Firmenfremder Verweis', + 'Auftrag mit Fahrer einer fremden Firma scheitert' +); + +-- Je ein gueltiger Auftrag pro Firma +update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, firma_id) values + ('a0000000-0000-0000-0000-0000000000e1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', + 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', '00000000-0000-0000-0000-00000000f001'), + ('b0000000-0000-0000-0000-0000000000e1', 'b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', + 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', '00000000-0000-0000-0000-00000000f002'); + +-- 11) Auftragsnummer zaehlt pro Firma: der erste B-Auftrag des Tages endet auf -0001 +select is( + (select right(auftragsnummer, 4) from public.auftraege where id = 'b0000000-0000-0000-0000-0000000000e1'), + '0001', + 'Auftragsnummer zaehlt pro Firma' +); + +-- 12) firma_id eines Auftrags ist unveraenderlich +select throws_ok( + $$ update public.auftraege set firma_id = '00000000-0000-0000-0000-00000000f002' + where id = 'a0000000-0000-0000-0000-0000000000e1' $$, + '42501', 'firma_id darf nicht geaendert werden', + 'firma_id eines Auftrags ist unveraenderlich' +); + +-- 13) WhatsApp-Outbox nur fuer Firma mit Empfaenger, mit firma_id aus dem Auftrag +select is( + (select count(*) from public.notification_outbox + where event_type = 'auftrag_erstellt' + and auftrag_id = 'a0000000-0000-0000-0000-0000000000e1' + and firma_id = '00000000-0000-0000-0000-00000000f001'), + 1::bigint, + 'Firma mit WhatsApp-Empfaenger bekommt eine Outbox-Zeile mit ihrer firma_id' +); +select is( + (select count(*) from public.notification_outbox where auftrag_id = 'b0000000-0000-0000-0000-0000000000e1'), + 0::bigint, + 'Firma ohne WhatsApp-Empfaenger bekommt keine Outbox-Zeile' +); + +-- 14a) FIN ist pro Firma eindeutig: gleiche FIN in f001 und f002 ist erlaubt +update public.fahrzeuge set fin = 'WVWZZZ1KZAW000002' where id = 'a0000000-0000-0000-0000-0000000000d1'; +select lives_ok( + $$ update public.fahrzeuge set fin = 'WVWZZZ1KZAW000002' where id = 'b0000000-0000-0000-0000-0000000000d1' $$, + 'Gleiche FIN in einer anderen Firma ist erlaubt' +); + +-- 14b) doppelte FIN in derselben Firma nicht +select throws_ok( + $$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) + values ('MT-AB 9', 'WVWZZZ1KZAW000002', '00000000-0000-0000-0000-00000000f001') $$, + '23505', null, + 'Doppelte FIN in derselben Firma scheitert' +); + +-- 14c) fin_bei_fahrtbeginn sucht nur in der eigenen Firma: eine FIN, die nur in +-- Firma B existiert, wird in Firma A nachgetragen und nicht als abweichend gemeldet. +insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values + ('b0000000-0000-0000-0000-0000000000d2', 'MT-BB 2', 'WDB9066331S555555', '00000000-0000-0000-0000-00000000f002'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('a0000000-0000-0000-0000-0000000000d2', 'MT-AB 2', '00000000-0000-0000-0000-00000000f001'); +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, zugewiesen_an, status, firma_id) values + ('a0000000-0000-0000-0000-0000000000e2', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', + 'a0000000-0000-0000-0000-0000000000d2', 'a0000000-0000-0000-0000-0000000000a1', + 'a0000000-0000-0000-0000-0000000000a3', 'zugewiesen', '00000000-0000-0000-0000-00000000f001'); + +set local role authenticated; +set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a3", "role": "authenticated"}'; +select is( + public.fin_bei_fahrtbeginn('a0000000-0000-0000-0000-0000000000e2', 'WDB9066331S555555'), + 'nachgetragen'::public.app_fin_abgleich, + 'FIN-Abgleich ignoriert FINs fremder Firmen (nachgetragen statt abweichend)' +); +reset role; +reset request.jwt.claims; + +select is( + (select fin from public.fahrzeuge where id = 'a0000000-0000-0000-0000-0000000000d2'), + 'WDB9066331S555555', + 'FIN steht am Fahrzeug der eigenen Firma' +); + +-- 15) Mit Nutzer-Session kann aktiv nicht geaendert werden. Nur Claims setzen, +-- Rolle bleibt postgres: in Task 1 gibt es noch keine Policy auf firmen, der +-- Trigger soll aber trotzdem greifen. +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; +select throws_ok( + $$ update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f002' $$, + '42501', 'Status und ID einer Firma kann nur der Plattform-Betreiber aendern', + 'Admin kann seine Firma nicht deaktivieren' +); +reset request.jwt.claims; + +-- 16) Deaktivierte Firma: user_firma_id() liefert null +update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f002'; +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; +select is((select public.user_firma_id()), null::uuid, 'Deaktivierte Firma: user_firma_id() ist null'); +reset role; +reset request.jwt.claims; + +select * from finish(); +rollback; diff --git a/supabase/tests/notification_outbox_rls_test.sql b/supabase/tests/notification_outbox_rls_test.sql index 45002da..ca460c8 100644 --- a/supabase/tests/notification_outbox_rls_test.sql +++ b/supabase/tests/notification_outbox_rls_test.sql @@ -5,15 +5,17 @@ insert into auth.users (id, email) values ('c1111111-1111-1111-1111-111111111111', 'admin-outbox@auftraege.test.local'), ('c2222222-2222-2222-2222-222222222222', 'disponent-outbox@auftraege.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; +update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; update public.profiles set role = 'admin' where id = 'c1111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'c2222222-2222-2222-2222-222222222222'; -insert into public.orte (id, adresse, ansprechpartner) values - ('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A'), - ('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A', '00000000-0000-0000-0000-00000000f001'), + ('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('c3333333-0000-0000-0000-000000000001', 'S-WA 42'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('c3333333-0000-0000-0000-000000000001', 'S-WA 42', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}'; @@ -105,20 +107,20 @@ delete from public.notification_outbox where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'; insert into public.notification_outbox - (id, event_type, status, payload, naechster_versuch_ab, updated_at) + (id, event_type, status, payload, naechster_versuch_ab, updated_at, firma_id) values -- faellig: pending, Zeitpunkt erreicht ('c5000000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, - now() - interval '1 minute', now()), + now() - interval '1 minute', now(), '00000000-0000-0000-0000-00000000f001'), -- nicht faellig: failed, Backoff noch in der Zukunft ('c5000000-0000-0000-0000-000000000002', 'auftrag_erstellt', 'failed', '{}'::jsonb, - now() + interval '1 hour', now()), + now() + interval '1 hour', now(), '00000000-0000-0000-0000-00000000f001'), -- nicht reclaimt: sending, erst vor 2 Minuten uebernommen ('c5000000-0000-0000-0000-000000000003', 'auftrag_erstellt', 'sending', '{}'::jsonb, - now(), now() - interval '2 minutes'), + now(), now() - interval '2 minutes', '00000000-0000-0000-0000-00000000f001'), -- reclaimt: sending, seit 20 Minuten haengengeblieben ('c5000000-0000-0000-0000-000000000004', 'auftrag_erstellt', 'sending', '{}'::jsonb, - now(), now() - interval '20 minutes'); + now(), now() - interval '20 minutes', '00000000-0000-0000-0000-00000000f001'); select results_eq( $$ select id::text from public.claim_notification_batch(10, array['auftrag_erstellt']) order by id $$, @@ -135,7 +137,7 @@ set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", -- wuerde die Beschreibung als erwartete Fehlermeldung interpretieren. Geprueft wird -- nur, dass der INSERT in SQLSTATE 42501 (RLS: keine INSERT-Policy) laeuft. select throws_ok( - $$ insert into public.notification_outbox (event_type, payload) values ('x', '{}'::jsonb) $$, + $$ insert into public.notification_outbox (event_type, payload, firma_id) values ('x', '{}'::jsonb, '00000000-0000-0000-0000-00000000f001') $$, '42501' ); diff --git a/supabase/tests/nutzer_details_rls_test.sql b/supabase/tests/nutzer_details_rls_test.sql index 27d63bb..6bc0558 100644 --- a/supabase/tests/nutzer_details_rls_test.sql +++ b/supabase/tests/nutzer_details_rls_test.sql @@ -7,6 +7,7 @@ insert into auth.users (id, email) values ('33333333-3333-3333-3333-333333333333', 'fahrer-a@test.local'), ('44444444-4444-4444-4444-444444444444', 'fahrer-b@test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = '22222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = '33333333-3333-3333-3333-333333333333'; diff --git a/supabase/tests/orte_fahrzeuge_rls_test.sql b/supabase/tests/orte_fahrzeuge_rls_test.sql index 6ad1783..1b91616 100644 --- a/supabase/tests/orte_fahrzeuge_rls_test.sql +++ b/supabase/tests/orte_fahrzeuge_rls_test.sql @@ -7,6 +7,7 @@ insert into auth.users (id, email) values ('f3333333-3333-3333-3333-333333333333', 'fahrer@stammdaten.test.local'), ('05555555-5555-5555-5555-555555555555', 'readonly@stammdaten.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'd2222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = 'f3333333-3333-3333-3333-333333333333'; diff --git a/supabase/tests/profiles_rls_test.sql b/supabase/tests/profiles_rls_test.sql index 7311df4..7007390 100644 --- a/supabase/tests/profiles_rls_test.sql +++ b/supabase/tests/profiles_rls_test.sql @@ -5,6 +5,7 @@ insert into auth.users (id, email) values ('11111111-1111-1111-1111-111111111111', 'admin@test.local'), ('22222222-2222-2222-2222-222222222222', 'fahrer@test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111'; update public.profiles set role = 'fahrer' where id = '22222222-2222-2222-2222-222222222222'; @@ -80,6 +81,9 @@ select is( -- Admin-Update zu 'disponent' geaendert). insert into auth.users (id, email) values ('44444444-4444-4444-4444-444444444444', 'fahrer2@test.local'); +-- Firmenzuordnung neuer Fixture-Nutzer: nur ohne JWT-Kontext erlaubt (Trigger firma_id_unveraenderlich) +reset request.jwt.claims; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'fahrer' where id = '44444444-4444-4444-4444-444444444444'; set local role authenticated; diff --git a/supabase/tests/protokoll_email_test.sql b/supabase/tests/protokoll_email_test.sql index 7408781..b807dca 100644 --- a/supabase/tests/protokoll_email_test.sql +++ b/supabase/tests/protokoll_email_test.sql @@ -7,23 +7,24 @@ insert into auth.users (id, email, raw_user_meta_data) values ('e5a00000-0000-0000-0000-000000000001', 'dispo-mail@test.local', '{}'::jsonb), ('e5a00000-0000-0000-0000-000000000002', null, '{"name": "Dispo ohne Mail"}'::jsonb); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'disponent' where id = 'e5a00000-0000-0000-0000-000000000001'; update public.profiles set role = 'disponent' where id = 'e5a00000-0000-0000-0000-000000000002'; -insert into public.orte (id, adresse, ansprechpartner) values - ('e5b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('e5b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('e5b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('e5b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('e5c00000-0000-0000-0000-000000000001', 'M-ML 001'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('e5c00000-0000-0000-0000-000000000001', 'M-ML 001', '00000000-0000-0000-0000-00000000f001'); -- A: Ersteller mit E-Mail, unterwegs -- B: Ersteller ohne E-Mail, unterwegs -- C: Ersteller mit E-Mail, zugewiesen (wird nur storniert) -insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, start_km) values - ('e5d00000-0000-0000-0000-00000000000a', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'unterwegs', 100), - ('e5d00000-0000-0000-0000-00000000000b', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000002', 'unterwegs', 100), - ('e5d00000-0000-0000-0000-00000000000c', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'zugewiesen', null); +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, start_km, firma_id) values + ('e5d00000-0000-0000-0000-00000000000a', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'unterwegs', 100, '00000000-0000-0000-0000-00000000f001'), + ('e5d00000-0000-0000-0000-00000000000b', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000002', 'unterwegs', 100, '00000000-0000-0000-0000-00000000f001'), + ('e5d00000-0000-0000-0000-00000000000c', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'zugewiesen', null, '00000000-0000-0000-0000-00000000f001'); -- 1) Abschluss legt genau eine Zeile an update public.auftraege @@ -88,9 +89,9 @@ select is( -- 6) claim_notification_batch claimt nur die angefragten Ereignis-Arten delete from public.notification_outbox; -insert into public.notification_outbox (id, event_type, status, payload, naechster_versuch_ab) values - ('e5e00000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, now() - interval '1 minute'), - ('e5e00000-0000-0000-0000-000000000002', 'protokoll_abgeschlossen', 'pending', '{}'::jsonb, now() - interval '1 minute'); +insert into public.notification_outbox (id, event_type, status, payload, naechster_versuch_ab, firma_id) values + ('e5e00000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, now() - interval '1 minute', '00000000-0000-0000-0000-00000000f001'), + ('e5e00000-0000-0000-0000-000000000002', 'protokoll_abgeschlossen', 'pending', '{}'::jsonb, now() - interval '1 minute', '00000000-0000-0000-0000-00000000f001'); select results_eq( $$ select id::text from public.claim_notification_batch(10, array['protokoll_abgeschlossen']) $$, diff --git a/supabase/tests/zeitplanung_test.sql b/supabase/tests/zeitplanung_test.sql index 9dba940..b947b33 100644 --- a/supabase/tests/zeitplanung_test.sql +++ b/supabase/tests/zeitplanung_test.sql @@ -3,14 +3,15 @@ select plan(5); insert into auth.users (id, email) values ('a1111111-1111-1111-1111-111111111111', 'admin@zeitplanung.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111'; -insert into public.orte (id, adresse, ansprechpartner) values - ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('f0000000-0000-0000-0000-000000000001', 'M-AB 123'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "a1111111-1111-1111-1111-111111111111", "role": "authenticated"}'; diff --git a/web/.env.local.example b/web/.env.local.example index 189c477..f70526d 100644 --- a/web/.env.local.example +++ b/web/.env.local.example @@ -18,7 +18,6 @@ SUPABASE_SERVICE_ROLE_KEY= WHATSAPP_ACCESS_TOKEN= WHATSAPP_PHONE_NUMBER_ID= # Feste Empfaenger-Sammelnummer, E.164 ohne fuehrendes "+" (z.B. 4915112345678). -WHATSAPP_RECIPIENT= # Name + Sprache des genehmigten Message-Templates. WHATSAPP_TEMPLATE_NAME=neuer_auftrag WHATSAPP_TEMPLATE_LANG=de @@ -28,3 +27,8 @@ WHATSAPP_GRAPH_VERSION= # /api/notifications/dispatch. MUSS mit dem DB-Setting # app.notification_dispatch_secret uebereinstimmen (siehe unten). NOTIFICATION_DISPATCH_SECRET= + +# --- Uebergabeprotokoll per E-Mail (SMTP) --- +# Schluessel fuer die SMTP-Passwoerter der Firmen (AES-256-GCM, 32 Byte base64). +# Erzeugen: openssl rand -base64 32 (Aendern macht gespeicherte Passwoerter unlesbar) +SMTP_VERSCHLUESSELUNG_KEY= diff --git a/web/app/abmelden/route.ts b/web/app/abmelden/route.ts new file mode 100644 index 0000000..268fc50 --- /dev/null +++ b/web/app/abmelden/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; +import { createClient } from "@/lib/supabase/server"; +import { FIRMA_GESPERRT } from "@/lib/firma/eigene-firma"; + +// Server Components koennen keine Cookies loeschen; das Layout leitet bei +// gesperrter Firma hierher um. +export async function GET(request: Request): Promise { + const supabase = await createClient(); + await supabase.auth.signOut(); + const ziel = new URL("/login", request.url); + if (new URL(request.url).searchParams.get("grund") === "firma") { + ziel.searchParams.set("error", FIRMA_GESPERRT); + } + return NextResponse.redirect(ziel); +} diff --git a/web/app/api/notifications/dispatch/route.test.ts b/web/app/api/notifications/dispatch/route.test.ts index 16931c8..02f7291 100644 --- a/web/app/api/notifications/dispatch/route.test.ts +++ b/web/app/api/notifications/dispatch/route.test.ts @@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("@/lib/supabase/admin", () => ({ createAdminClient: vi.fn(() => ({})) })); vi.mock("@/lib/notifications/config", () => ({ getWhatsAppConfig: vi.fn() })); vi.mock("@/lib/notifications/dispatch", () => ({ verarbeiteOutbox: vi.fn() })); -vi.mock("@/lib/notifications/email-config", () => ({ getEmailConfig: vi.fn() })); vi.mock("@/lib/notifications/handler", () => ({ whatsappHandler: vi.fn(() => "wa-handler"), protokollMailHandler: vi.fn(() => "mail-handler"), @@ -11,13 +10,11 @@ vi.mock("@/lib/notifications/handler", () => ({ import { getWhatsAppConfig } from "@/lib/notifications/config"; import { verarbeiteOutbox } from "@/lib/notifications/dispatch"; -import { getEmailConfig } from "@/lib/notifications/email-config"; import { POST } from "./route"; const CFG = { accessToken: "tok", phoneNumberId: "PN1", - recipient: "4915100000000", templateName: "neuer_auftrag", templateLang: "de", graphVersion: "v21.0", @@ -35,7 +32,6 @@ beforeEach(() => { altSecret = process.env.NOTIFICATION_DISPATCH_SECRET; process.env.NOTIFICATION_DISPATCH_SECRET = "geheim"; vi.mocked(getWhatsAppConfig).mockReset(); - vi.mocked(getEmailConfig).mockReset(); vi.mocked(verarbeiteOutbox).mockReset(); fehlerSpy = vi.spyOn(console, "error").mockImplementation(() => {}); warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); @@ -78,18 +74,8 @@ describe("POST /api/notifications/dispatch", () => { expect(await res.json()).toEqual({ fehler: "Unauthorized" }); }); - it("antwortet 200 uebersprungen, wenn kein Kanal konfiguriert ist", async () => { - vi.mocked(getWhatsAppConfig).mockReturnValue(null); - vi.mocked(getEmailConfig).mockReturnValue(null); - const res = await POST(req({ Authorization: "Bearer geheim" })); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ verarbeitet: 0, uebersprungen: true }); - expect(verarbeiteOutbox).not.toHaveBeenCalled(); - }); - it("ruft verarbeiteOutbox und gibt dessen Ergebnis als 200 zurueck", async () => { vi.mocked(getWhatsAppConfig).mockReturnValue(CFG); - vi.mocked(getEmailConfig).mockReturnValue(null); vi.mocked(verarbeiteOutbox).mockResolvedValue({ verarbeitet: 2, gesendet: 1, @@ -100,12 +86,14 @@ describe("POST /api/notifications/dispatch", () => { expect(res.status).toBe(200); expect(await res.json()).toEqual({ verarbeitet: 2, gesendet: 1, fehlgeschlagen: 1, tot: 0 }); expect(verarbeiteOutbox).toHaveBeenCalledOnce(); - expect(verarbeiteOutbox).toHaveBeenCalledWith({}, { auftrag_erstellt: "wa-handler" }); + expect(verarbeiteOutbox).toHaveBeenCalledWith({}, { + protokoll_abgeschlossen: "mail-handler", + auftrag_erstellt: "wa-handler", + }); }); it("verarbeitet Protokoll-Mails auch ohne WhatsApp-Config", async () => { vi.mocked(getWhatsAppConfig).mockReturnValue(null); - vi.mocked(getEmailConfig).mockReturnValue({ host: "smtp", port: 587, secure: false, from: "x@y.de", auth: null }); vi.mocked(verarbeiteOutbox).mockResolvedValue({ verarbeitet: 1, gesendet: 1, fehlgeschlagen: 0, tot: 0 }); const res = await POST(req({ Authorization: "Bearer geheim" })); diff --git a/web/app/api/notifications/dispatch/route.ts b/web/app/api/notifications/dispatch/route.ts index 0f70f20..f4e00d9 100644 --- a/web/app/api/notifications/dispatch/route.ts +++ b/web/app/api/notifications/dispatch/route.ts @@ -2,7 +2,6 @@ import { NextResponse } from "next/server"; import { timingSafeEqual } from "node:crypto"; import { createAdminClient } from "@/lib/supabase/admin"; import { getWhatsAppConfig } from "@/lib/notifications/config"; -import { getEmailConfig } from "@/lib/notifications/email-config"; import { verarbeiteOutbox, type Handler } from "@/lib/notifications/dispatch"; import { protokollMailHandler, whatsappHandler } from "@/lib/notifications/handler"; @@ -38,20 +37,14 @@ export async function POST(request: Request): Promise { const handler: Record = {}; const waCfg = getWhatsAppConfig(); - const mailCfg = getEmailConfig(); - - if (!waCfg && !mailCfg) { - console.warn("[notifications] kein Kanal konfiguriert – Outbox wird nicht verarbeitet"); - return NextResponse.json({ verarbeitet: 0, uebersprungen: true }); - } try { const admin = createAdminClient(); + // Protokoll-Mails werden immer geclaimt: ob ein SMTP existiert, steht erst + // pro Zeile fest (Firmen-SMTP oder globaler Fallback). + handler.protokoll_abgeschlossen = protokollMailHandler(admin); if (waCfg) { - handler.auftrag_erstellt = whatsappHandler(waCfg); - } - if (mailCfg) { - handler.protokoll_abgeschlossen = protokollMailHandler(admin, mailCfg); + handler.auftrag_erstellt = whatsappHandler(admin, waCfg); } const ergebnis = await verarbeiteOutbox(admin, handler); return NextResponse.json(ergebnis); diff --git a/web/app/firma/actions.ts b/web/app/firma/actions.ts new file mode 100644 index 0000000..09cfba9 --- /dev/null +++ b/web/app/firma/actions.ts @@ -0,0 +1,72 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { createClient } from "@/lib/supabase/server"; +import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; +import { validateFirmaEinstellungen } from "@/lib/firma/einstellungen"; +import { logoPfad, validateLogo } from "@/lib/firma/logo"; + +export type ActionResult = { success: true } | { success: false; error: string }; + +export async function speichereFirmaEinstellungen(formData: FormData): Promise { + const kontext = await ladeAdminKontext(); + if (!kontext.ok) return { success: false, error: kontext.error }; + + const validation = validateFirmaEinstellungen({ + name: formData.get("name"), + whatsapp: formData.get("whatsapp_empfaenger"), + standardFarben: formData.get("standard_farben") === "on", + farbePrimaer: formData.get("farbe_primaer"), + farbeDunkel: formData.get("farbe_dunkel"), + }); + if (!validation.valid) return { success: false, error: validation.error }; + + const supabase = await createClient(); + const { data, error } = await supabase.from("firmen").update(validation.werte).eq("id", kontext.firma.id).select("id"); + if (error || !data || data.length === 0) { + return { success: false, error: "Speichern fehlgeschlagen." }; + } + revalidatePath("/", "layout"); + return { success: true }; +} + +export async function ladeLogoHoch(formData: FormData): Promise { + const kontext = await ladeAdminKontext(); + if (!kontext.ok) return { success: false, error: kontext.error }; + + const datei = formData.get("logo"); + if (!(datei instanceof File)) return { success: false, error: "Bitte eine Datei auswählen." }; + const validation = validateLogo({ type: datei.type, size: datei.size }); + if (!validation.valid) return { success: false, error: validation.error }; + + const supabase = await createClient(); + const pfad = logoPfad(kontext.firma.id, validation.endung); + const { error: uploadFehler } = await supabase.storage + .from("firmen-logos") + .upload(pfad, datei, { contentType: datei.type }); + if (uploadFehler) return { success: false, error: "Logo-Upload fehlgeschlagen." }; + + const { error } = await supabase.from("firmen").update({ logo_pfad: pfad }).eq("id", kontext.firma.id); + if (error) { + await supabase.storage.from("firmen-logos").remove([pfad]); + return { success: false, error: "Logo konnte nicht gespeichert werden." }; + } + if (kontext.firma.logo_pfad) { + await supabase.storage.from("firmen-logos").remove([kontext.firma.logo_pfad]); + } + revalidatePath("/", "layout"); + return { success: true }; +} + +export async function entferneLogo(): Promise { + const kontext = await ladeAdminKontext(); + if (!kontext.ok) return { success: false, error: kontext.error }; + if (!kontext.firma.logo_pfad) return { success: true }; + + const supabase = await createClient(); + const { error } = await supabase.from("firmen").update({ logo_pfad: null }).eq("id", kontext.firma.id); + if (error) return { success: false, error: "Logo konnte nicht entfernt werden." }; + await supabase.storage.from("firmen-logos").remove([kontext.firma.logo_pfad]); + revalidatePath("/", "layout"); + return { success: true }; +} diff --git a/web/app/firma/logo/route.ts b/web/app/firma/logo/route.ts new file mode 100644 index 0000000..370a8d1 --- /dev/null +++ b/web/app/firma/logo/route.ts @@ -0,0 +1,27 @@ +import { createClient } from "@/lib/supabase/server"; +import { ladeEigeneFirma } from "@/lib/firma/eigene-firma"; +import { LOGO_SICHERHEITS_HEADER, logoContentType } from "@/lib/firma/logo"; + +export const dynamic = "force-dynamic"; + +// Signierte Storage-URLs scheiden aus: im Docker-Stack enthielten sie die +// interne Kong-Adresse. Die Datei wird mit dem Nutzer-Client geladen (RLS). +export async function GET(): Promise { + const ergebnis = await ladeEigeneFirma(); + if (ergebnis.status !== "ok" || !ergebnis.firma.logo_pfad) { + return new Response(null, { status: 404 }); + } + const pfad = ergebnis.firma.logo_pfad; + const supabase = await createClient(); + const { data, error } = await supabase.storage.from("firmen-logos").download(pfad); + if (error || !data) { + return new Response(null, { status: 404 }); + } + return new Response(await data.arrayBuffer(), { + headers: { + "Content-Type": logoContentType(pfad), + "Cache-Control": "private, max-age=86400", + ...LOGO_SICHERHEITS_HEADER, + }, + }); +} diff --git a/web/app/firma/page.tsx b/web/app/firma/page.tsx new file mode 100644 index 0000000..6b7e9b7 --- /dev/null +++ b/web/app/firma/page.tsx @@ -0,0 +1,47 @@ +import { redirect } from "next/navigation"; +import { createAdminClient } from "@/lib/supabase/admin"; +import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; +import { ladeFirmenSmtp, type SmtpAnzeige } from "@/lib/firma/smtp"; +import { FirmaEinstellungenForm } from "@/components/firma/FirmaEinstellungenForm"; +import { LogoForm } from "@/components/firma/LogoForm"; +import { SmtpForm } from "@/components/firma/SmtpForm"; +import { Card } from "@/components/ui/Card"; + +export default async function FirmaPage() { + const kontext = await ladeAdminKontext(); + if (!kontext.ok) { + redirect("/dashboard"); + } + + // Das Passwort verlaesst den Server nie, nur ob eins gesetzt ist. + const zeile = await ladeFirmenSmtp(createAdminClient(), kontext.firma.id); + const smtp: SmtpAnzeige | null = zeile + ? { + host: zeile.host, + port: zeile.port, + secure: zeile.secure, + benutzer: zeile.benutzer, + absender_adresse: zeile.absender_adresse, + absender_name: zeile.absender_name, + passwortGesetzt: Boolean(zeile.passwort_verschluesselt), + } + : null; + + return ( +
+

Firma

+ +

Allgemein

+ +
+ +

Logo

+ +
+ +

E-Mail-Versand (SMTP)

+ +
+
+ ); +} diff --git a/web/app/firma/smtp-actions.ts b/web/app/firma/smtp-actions.ts new file mode 100644 index 0000000..76792b5 --- /dev/null +++ b/web/app/firma/smtp-actions.ts @@ -0,0 +1,120 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { createClient } from "@/lib/supabase/server"; +import { createAdminClient } from "@/lib/supabase/admin"; +import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; +import { + SMTP_ZIEL_NICHT_ERLAUBT, + SmtpZielFehler, + firmenSmtpZuConfig, + ladeFirmenSmtp, + pinneSmtpZiel, + validateSmtpEingabe, +} from "@/lib/firma/smtp"; +import { verschluessele } from "@/lib/firma/smtp-crypto"; +import { pruefeSmtpZiel } from "@/lib/firma/smtp-ziel"; +import { sendeProtokollMail } from "@/lib/notifications/email"; + +export type ActionResult = { success: true } | { success: false; error: string }; + +// firmen_smtp ist nur per Service-Client erreichbar. Deshalb vorher ueber den +// RLS-Client pruefen (ladeAdminKontext), die firma_id kommt nur von dort. +export async function speichereSmtp(formData: FormData): Promise { + const kontext = await ladeAdminKontext(); + if (!kontext.ok) return { success: false, error: kontext.error }; + + const admin = createAdminClient(); + const bestehend = await ladeFirmenSmtp(admin, kontext.firma.id); + + const validation = validateSmtpEingabe( + { + host: formData.get("host"), + port: formData.get("port"), + secure: formData.get("secure") === "on", + benutzer: formData.get("benutzer"), + passwort: formData.get("passwort"), + absenderAdresse: formData.get("absender_adresse"), + absenderName: formData.get("absender_name"), + }, + bestehend + ); + if (!validation.valid) return { success: false, error: validation.error }; + const w = validation.werte; + + const ziel = await pruefeSmtpZiel(w.host); + if (!ziel.ok) return { success: false, error: `${SMTP_ZIEL_NICHT_ERLAUBT}.` }; + + let passwortVerschluesselt: string | null = null; + if (w.benutzer) { + try { + passwortVerschluesselt = w.neuesPasswort + ? verschluessele(w.neuesPasswort) + : w.passwortBehalten + ? (bestehend?.passwort_verschluesselt ?? null) + : null; + } catch (fehler) { + return { success: false, error: fehler instanceof Error ? fehler.message : "Verschlüsselung fehlgeschlagen." }; + } + } + + const { error } = await admin.from("firmen_smtp").upsert( + { + firma_id: kontext.firma.id, + host: w.host, + port: w.port, + secure: w.secure, + benutzer: w.benutzer, + passwort_verschluesselt: passwortVerschluesselt, + absender_adresse: w.absender_adresse, + absender_name: w.absender_name, + updated_at: new Date().toISOString(), + }, + { onConflict: "firma_id" } + ); + if (error) return { success: false, error: "SMTP-Einstellungen konnten nicht gespeichert werden." }; + revalidatePath("/firma"); + return { success: true }; +} + +export async function entferneSmtp(): Promise { + 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); + if (error) return { success: false, error: "SMTP-Einstellungen konnten nicht entfernt werden." }; + revalidatePath("/firma"); + return { success: true }; +} + +export async function sendeTestmail(): Promise { + const kontext = await ladeAdminKontext(); + if (!kontext.ok) return { success: false, error: kontext.error }; + + const supabase = await createClient(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user?.email) return { success: false, error: "Für Ihren Zugang ist keine E-Mail-Adresse hinterlegt." }; + + const zeile = await ladeFirmenSmtp(createAdminClient(), kontext.firma.id); + if (!zeile) return { success: false, error: "Es ist noch kein eigener SMTP-Server gespeichert." }; + + let cfg; + try { + cfg = await pinneSmtpZiel(firmenSmtpZuConfig(zeile)); + } catch (fehler) { + if (fehler instanceof SmtpZielFehler) return { success: false, error: `${SMTP_ZIEL_NICHT_ERLAUBT}.` }; + return { success: false, error: fehler instanceof Error ? fehler.message : "Konfiguration ungültig." }; + } + + const ergebnis = await sendeProtokollMail(cfg, { + to: user.email, + subject: `Testmail ${kontext.firma.name}`, + text: "Diese Testmail bestätigt, dass der SMTP-Versand Ihrer Firma funktioniert.", + attachments: [], + }); + if (ergebnis.ok) return { success: true }; + // Kein Rohtext an den Admin: Fehlermeldungen koennten interne Ziele verraten. + console.error("Testmail fehlgeschlagen:", ergebnis.fehler); + return { success: false, error: "Verbindung zum SMTP-Server fehlgeschlagen." }; +} diff --git a/web/app/layout.tsx b/web/app/layout.tsx index 2f82e23..907667e 100644 --- a/web/app/layout.tsx +++ b/web/app/layout.tsx @@ -1,8 +1,11 @@ -import Image from "next/image"; import Link from "next/link"; +import { redirect } from "next/navigation"; import { Inter } from "next/font/google"; import "./globals.css"; import { loadProfile } from "@/lib/auth/profile"; +import { ladeEigeneFirma } from "@/lib/firma/eigene-firma"; +import { themeVariablen } from "@/lib/firma/farben"; +import { FirmenLogo } from "@/components/FirmenLogo"; import { NavLinks } from "@/components/NavLinks"; import { LogoutButton } from "@/components/LogoutButton"; import { MobileNav } from "@/components/MobileNav"; @@ -17,6 +20,12 @@ export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { const result = await loadProfile(); + const firmaErgebnis = await ladeEigeneFirma(); + if (result.status === "ok" && firmaErgebnis.status === "keine-firma") { + redirect("/abmelden?grund=firma"); + } + const firma = firmaErgebnis.status === "ok" ? firmaErgebnis.firma : null; + const themeStyle = firma ? (themeVariablen(firma) as React.CSSProperties) : undefined; if (result.status === "missing-profile") { return ( @@ -36,12 +45,12 @@ export default async function RootLayout({ } return ( - + {result.status === "ok" && (
- - Widmann + +
diff --git a/web/app/login/actions.ts b/web/app/login/actions.ts index 70f9947..b127cb8 100644 --- a/web/app/login/actions.ts +++ b/web/app/login/actions.ts @@ -4,9 +4,12 @@ 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 { const validation = validateLogin({ @@ -57,7 +60,25 @@ export async function login(formData: FormData): Promise { redirect(`/login?error=${encodeURIComponent(LOGIN_FEHLER)}`); } - redirect(hatPasswortAenderPflicht(data.user) ? PASSWORT_AENDERN_PFAD : "/dashboard"); + let zugang: Awaited> | 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 { diff --git a/web/app/nutzerverwaltung/actions.ts b/web/app/nutzerverwaltung/actions.ts index 443510f..0f30e3b 100644 --- a/web/app/nutzerverwaltung/actions.ts +++ b/web/app/nutzerverwaltung/actions.ts @@ -4,6 +4,7 @@ import { redirect } from "next/navigation"; import { createClient } from "@/lib/supabase/server"; import { createAdminClient } from "@/lib/supabase/admin"; import { loadProfile } from "@/lib/auth/profile"; +import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; import { canManageUsers } from "@/lib/auth/roles"; import { validateNutzerErstellen, @@ -13,15 +14,19 @@ import { import { validatePasswort } from "@/lib/auth/passwort"; import { validateNutzerDetails, leseDetailsAusFormData } from "@/lib/nutzerverwaltung/details"; import { speichereDetails } from "@/lib/nutzerverwaltung/details-queries"; +import { legeNutzerInFirmaAn } from "@/lib/nutzerverwaltung/nutzer-anlegen"; +import { pruefeZielNutzer } from "@/lib/nutzerverwaltung/ziel-pruefen"; export type ActionResult = { success: true } | { success: false; error: string }; const USERNAME_VERGEBEN = "Dieser Benutzername ist bereits vergeben."; +const NICHT_GEFUNDEN = "Nutzer nicht gefunden."; export async function erstelleNutzer(formData: FormData): Promise { - const profileResult = await loadProfile(); - if (profileResult.status !== "ok" || !canManageUsers(profileResult.profile.role)) { - redirect(`/nutzerverwaltung?error=${encodeURIComponent("Nur Admin darf Nutzer anlegen.")}`); + // Aktive Firma ueber den RLS-Client; deaktivierte Firmen koennen keine Nutzer anlegen. + const kontext = await ladeAdminKontext(); + if (!kontext.ok) { + redirect(`/nutzerverwaltung?error=${encodeURIComponent(kontext.error)}`); } const validation = validateNutzerErstellen({ @@ -35,33 +40,19 @@ export async function erstelleNutzer(formData: FormData): Promise { redirect(`/nutzerverwaltung?error=${encodeURIComponent(validation.error)}`); } - const adminClient = createAdminClient(); - const { data: erstellt, error: erstellFehler } = await adminClient.auth.admin.createUser({ + const ergebnis = await legeNutzerInFirmaAn(createAdminClient(), { + firmaId: kontext.firma.id, + name: validation.name, email: validation.email, - password: validation.passwort, - email_confirm: true, - user_metadata: { name: validation.name }, - app_metadata: { must_change_password: true }, + passwort: validation.passwort, + rolle: validation.rolle as "admin" | "disponent" | "fahrer" | "readonly", + username: validation.username, }); - - if (erstellFehler || !erstellt.user) { - redirect( - `/nutzerverwaltung?error=${encodeURIComponent(`Nutzer anlegen fehlgeschlagen: ${erstellFehler?.message ?? "Unbekannter Fehler"}`)}` - ); + if (!ergebnis.ok) { + redirect(`/nutzerverwaltung?error=${encodeURIComponent(ergebnis.fehler)}`); } - - const supabase = await createClient(); - const { error: profilFehler } = await supabase - .from("profiles") - .update({ role: validation.rolle, username: validation.username }) - .eq("id", erstellt.user.id); - - if (profilFehler) { - const nachricht = - profilFehler.code === "23505" - ? "Nutzer wurde angelegt, der gewaehlte Benutzername ist aber bereits vergeben. Der neue Nutzer erscheint mit einem automatisch vergebenen Platzhalter-Benutzernamen in der Liste unten, dort kann er angepasst werden." - : `Nutzer wurde angelegt, Rolle/Benutzername konnten aber nicht gesetzt werden: ${profilFehler.message}`; - redirect(`/nutzerverwaltung?error=${encodeURIComponent(nachricht)}`); + if (ergebnis.usernameHinweis) { + redirect(`/nutzerverwaltung?error=${encodeURIComponent(ergebnis.usernameHinweis)}`); } redirect("/nutzerverwaltung"); @@ -89,9 +80,9 @@ export async function aktualisiereNutzer(nutzerId: string, formData: FormData): } const supabase = await createClient(); - const { data: aktuellesProfil } = await supabase.from("profiles").select("role").eq("id", nutzerId).single(); + const aktuellesProfil = await pruefeZielNutzer(supabase, nutzerId); if (!aktuellesProfil) { - return { success: false, error: "Nutzer nicht gefunden." }; + return { success: false, error: NICHT_GEFUNDEN }; } if (istSelbstschutzVerletzt(profileResult.profile.id, nutzerId) && validation.rolle !== aktuellesProfil.role) { @@ -146,6 +137,11 @@ export async function sperreNutzer(nutzerId: string): Promise { return { success: false, error: "Der eigene Account kann nicht selbst gesperrt werden." }; } + const supabase = await createClient(); + if (!(await pruefeZielNutzer(supabase, nutzerId))) { + return { success: false, error: NICHT_GEFUNDEN }; + } + const adminClient = createAdminClient(); const { error } = await adminClient.auth.admin.updateUserById(nutzerId, { ban_duration: "876000h" }); if (error) { @@ -161,6 +157,11 @@ export async function entsperreNutzer(nutzerId: string): Promise { return { success: false, error: "Nur Admin darf Nutzer entsperren." }; } + const supabase = await createClient(); + if (!(await pruefeZielNutzer(supabase, nutzerId))) { + return { success: false, error: NICHT_GEFUNDEN }; + } + const adminClient = createAdminClient(); const { error } = await adminClient.auth.admin.updateUserById(nutzerId, { ban_duration: "none" }); if (error) { @@ -185,6 +186,11 @@ export async function setzePasswort(nutzerId: string, formData: FormData): Promi return { success: false, error: validation.error }; } + const supabase = await createClient(); + if (!(await pruefeZielNutzer(supabase, nutzerId))) { + return { success: false, error: NICHT_GEFUNDEN }; + } + const adminClient = createAdminClient(); const { error } = await adminClient.auth.admin.updateUserById(nutzerId, { password: validation.passwort, diff --git a/web/app/plattform/[id]/page.tsx b/web/app/plattform/[id]/page.tsx new file mode 100644 index 0000000..de28a83 --- /dev/null +++ b/web/app/plattform/[id]/page.tsx @@ -0,0 +1,88 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { createAdminClient } from "@/lib/supabase/admin"; +import { loadProfile } from "@/lib/auth/profile"; +import { pruefeSuperadmin } from "@/lib/plattform/superadmin"; +import { ladeFirmaFuerPlattform, listFirmenAdmins } from "@/lib/plattform/queries"; +import { legeFirmenAdminAn, setzeAdminPasswort, setzeFirmaAktiv } from "../actions"; +import { Alert } from "@/components/ui/Alert"; +import { Button } from "@/components/ui/Button"; +import { Card } from "@/components/ui/Card"; +import { FIELD_CLASSES, FormField } from "@/components/ui/FormField"; + +export default async function PlattformFirmaPage({ + params, + searchParams, +}: { + params: Promise<{ id: string }>; + searchParams: Promise<{ error?: string }>; +}) { + if (!pruefeSuperadmin(await loadProfile())) { + redirect("/dashboard"); + } + const { id } = await params; + const { error } = await searchParams; + const admin = createAdminClient(); + const firma = await ladeFirmaFuerPlattform(admin, id); + if (!firma) notFound(); + const admins = await listFirmenAdmins(admin, id); + + return ( +
+ + ← Alle Firmen + +

{firma.name}

+ {error && {error}} + + +

+ Status: {firma.aktiv ? "aktiv" : deaktiviert} +

+
+ +
+
+ + +

Admins

+
    + {admins.map((a) => ( +
  • +

    {a.name}

    +

    + {a.email ?? "-"} · {a.username} +

    +
    + + + + +
    +
  • + ))} +
+
+ + +

Weiteren Admin anlegen

+
+ + + + + + + + + + +
+
+
+ ); +} diff --git a/web/app/plattform/actions.ts b/web/app/plattform/actions.ts new file mode 100644 index 0000000..cfd2a48 --- /dev/null +++ b/web/app/plattform/actions.ts @@ -0,0 +1,91 @@ +"use server"; + +import { redirect } from "next/navigation"; +import { revalidatePath } from "next/cache"; +import { createAdminClient } from "@/lib/supabase/admin"; +import { loadProfile } from "@/lib/auth/profile"; +import { validatePasswort } from "@/lib/auth/passwort"; +import { legeNutzerInFirmaAn } from "@/lib/nutzerverwaltung/nutzer-anlegen"; +import { pruefeSuperadmin } from "@/lib/plattform/superadmin"; +import { validateFirmaAnlegen, validateFirmenAdmin } from "@/lib/plattform/validate"; + +function zurueck(pfad: string, fehler?: string): never { + redirect(fehler ? `${pfad}?error=${encodeURIComponent(fehler)}` : pfad); +} + +async function sicherSuperadmin(): Promise { + if (!pruefeSuperadmin(await loadProfile())) { + redirect("/login"); + } +} + +export async function legeFirmaAn(formData: FormData): Promise { + await sicherSuperadmin(); + const v = validateFirmaAnlegen({ + firmenname: formData.get("firmenname"), + name: formData.get("name"), + email: formData.get("email"), + passwort: formData.get("passwort"), + }); + if (!v.valid) zurueck("/plattform", v.error); + + const admin = createAdminClient(); + 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 }); + if (!nutzer.ok) { + // Keine Firma ohne Admin zuruecklassen. + const { error: loeschFehler } = await admin.from("firmen").delete().eq("id", firma.id); + if (loeschFehler) { + console.error(`Rollback: Firma ${firma.id} konnte nicht geloescht werden: ${loeschFehler.message}`); + } + zurueck("/plattform", nutzer.fehler); + } + revalidatePath("/plattform"); + zurueck(`/plattform/${firma.id}`); +} + +export async function setzeFirmaAktiv(firmaId: string, aktiv: boolean): Promise { + await sicherSuperadmin(); + const { error } = await createAdminClient().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 { + 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(), { + firmaId, + rolle: "admin", + name: v.name, + email: v.email, + passwort: v.passwort, + }); + zurueck(`/plattform/${firmaId}`, nutzer.ok ? undefined : nutzer.fehler); +} + +export async function setzeAdminPasswort(firmaId: string, nutzerId: string, formData: FormData): Promise { + await sicherSuperadmin(); + const v = validatePasswort(formData.get("passwort")); + if (!v.valid) zurueck(`/plattform/${firmaId}`, v.error); + + const admin = createAdminClient(); + // Nur Admins der angegebenen Firma, nie andere Rollen oder Superadmins. + const { data: ziel } = await admin + .from("profiles") + .select("id") + .eq("id", nutzerId) + .eq("firma_id", firmaId) + .eq("role", "admin") + .maybeSingle(); + if (!ziel) zurueck(`/plattform/${firmaId}`, "Nutzer nicht gefunden."); + + const { error } = await admin.auth.admin.updateUserById(nutzerId, { + password: v.passwort, + app_metadata: { must_change_password: true }, + }); + zurueck(`/plattform/${firmaId}`, error ? `Passwort setzen fehlgeschlagen: ${error.message}` : undefined); +} diff --git a/web/app/plattform/page.tsx b/web/app/plattform/page.tsx new file mode 100644 index 0000000..273e5df --- /dev/null +++ b/web/app/plattform/page.tsx @@ -0,0 +1,61 @@ +import Link from "next/link"; +import { redirect } from "next/navigation"; +import { createAdminClient } from "@/lib/supabase/admin"; +import { loadProfile } from "@/lib/auth/profile"; +import { pruefeSuperadmin } from "@/lib/plattform/superadmin"; +import { listFirmen } from "@/lib/plattform/queries"; +import { legeFirmaAn } from "./actions"; +import { Alert } from "@/components/ui/Alert"; +import { Button } from "@/components/ui/Button"; +import { Card } from "@/components/ui/Card"; +import { FIELD_CLASSES, FormField } from "@/components/ui/FormField"; + +export default async function PlattformPage({ searchParams }: { searchParams: Promise<{ error?: string }> }) { + if (!pruefeSuperadmin(await loadProfile())) { + redirect("/dashboard"); + } + const { error } = await searchParams; + const firmen = await listFirmen(createAdminClient()); + + return ( +
+

Plattform-Verwaltung

+ {error && {error}} + + +

Firmen

+
    + {firmen.map((f) => ( +
  • + + {f.name} + + {f.nutzerAnzahl} Nutzer · {f.aktiv ? "aktiv" : deaktiviert} + + +
  • + ))} +
+
+ + +

Neue Firma anlegen

+
+ + + + + + + + + + + + + +
+
+
+ ); +} diff --git a/web/app/profil/actions.ts b/web/app/profil/actions.ts index 6539ff7..d481bcd 100644 --- a/web/app/profil/actions.ts +++ b/web/app/profil/actions.ts @@ -14,6 +14,10 @@ export async function speichereMeineDaten(formData: FormData): Promise

Mein Profil

{profileResult.profile.name}

- + {!details ? ( +

Für den Plattform-Zugang gibt es keine Kontaktdaten.

+ ) : ( + + )}
); diff --git a/web/components/FirmenLogo.tsx b/web/components/FirmenLogo.tsx new file mode 100644 index 0000000..448bfa3 --- /dev/null +++ b/web/components/FirmenLogo.tsx @@ -0,0 +1,22 @@ +import Image from "next/image"; +import { WIDMANN_FIRMA_ID, type Firma } from "@/lib/firma/queries"; + +export function FirmenLogo({ firma }: { firma: Firma | null }) { + if (!firma) { + return Plattform-Verwaltung; + } + if (firma.logo_pfad) { + return ( + // eslint-disable-next-line @next/next/no-img-element -- Logo kommt aus einer eigenen Route mit Session-Cookie + {firma.name} + ); + } + if (firma.id === WIDMANN_FIRMA_ID) { + return Widmann; + } + return {firma.name}; +} diff --git a/web/components/NavLinks.tsx b/web/components/NavLinks.tsx index fad29cf..d92dd9d 100644 --- a/web/components/NavLinks.tsx +++ b/web/components/NavLinks.tsx @@ -1,5 +1,5 @@ import Link from "next/link"; -import { canManageUsers, kannAuslastungSehen, kannFahrerdetailsSehen, kannStammdatenPflegen, kannZeiterfassungNutzen, type Role } from "@/lib/auth/roles"; +import { canManageUsers, istSuperadmin, kannFirmaVerwalten, kannAuslastungSehen, kannFahrerdetailsSehen, kannStammdatenPflegen, kannZeiterfassungNutzen, type Role } from "@/lib/auth/roles"; export function NavLinks({ role, @@ -10,6 +10,22 @@ export function NavLinks({ }) { const layoutClass = orientation === "horizontal" ? "flex flex-row items-center gap-6" : "flex flex-col gap-4"; + const linkClass = + "flex min-h-11 items-center text-asphalt-grey hover:text-performance-blue focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-performance-blue"; + + if (istSuperadmin(role)) { + return ( + + ); + } + return (