forked from fahrPool/fahrPool
feat: Firmenzugang beim Login, Branding im Layout, Logo-Route, Superadmin-Navigation
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
88693282f8
commit
61f531552c
|
|
@ -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<Response> {
|
||||
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);
|
||||
}
|
||||
|
|
@ -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<Response> {
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<html lang="de" className={inter.variable}>
|
||||
<html lang="de" className={inter.variable} style={themeStyle}>
|
||||
<body className="flex min-h-screen flex-col font-sans">
|
||||
{result.status === "ok" && (
|
||||
<header className="flex h-16 items-center justify-between border-b border-aluminium-grey px-4 lg:px-8">
|
||||
<Link href="/dashboard" className="flex items-center">
|
||||
<Image src="/brand/widmann-logo.svg" alt="Widmann" width={140} height={21} priority />
|
||||
<Link href={result.profile.role === "superadmin" ? "/plattform" : "/dashboard"} className="flex items-center">
|
||||
<FirmenLogo firma={firma} />
|
||||
</Link>
|
||||
|
||||
<div className="hidden items-center gap-6 lg:flex">
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ 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.";
|
||||
|
|
@ -57,7 +59,16 @@ export async function login(formData: FormData): Promise<void> {
|
|||
redirect(`/login?error=${encodeURIComponent(LOGIN_FEHLER)}`);
|
||||
}
|
||||
|
||||
redirect(hatPasswortAenderPflicht(data.user) ? PASSWORT_AENDERN_PFAD : "/dashboard");
|
||||
const zugang = await pruefeFirmenzugang(supabase, data.user.id);
|
||||
if (zugang === "gesperrt") {
|
||||
await supabase.auth.signOut();
|
||||
redirect(`/login?error=${encodeURIComponent(FIRMA_GESPERRT)}`);
|
||||
}
|
||||
|
||||
if (hatPasswortAenderPflicht(data.user)) {
|
||||
redirect(PASSWORT_AENDERN_PFAD);
|
||||
}
|
||||
redirect(zugang === "superadmin" ? "/plattform" : "/dashboard");
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -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 <span className="font-semibold text-night-blue">Plattform-Verwaltung</span>;
|
||||
}
|
||||
if (firma.logo_pfad) {
|
||||
return (
|
||||
// eslint-disable-next-line @next/next/no-img-element -- Logo kommt aus einer eigenen Route mit Session-Cookie
|
||||
<img
|
||||
src={`/firma/logo?v=${encodeURIComponent(firma.logo_pfad)}`}
|
||||
alt={firma.name}
|
||||
className="h-8 w-auto max-w-[180px] object-contain"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (firma.id === WIDMANN_FIRMA_ID) {
|
||||
return <Image src="/brand/widmann-logo.svg" alt="Widmann" width={140} height={21} priority />;
|
||||
}
|
||||
return <span className="font-semibold text-night-blue">{firma.name}</span>;
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<nav className={layoutClass}>
|
||||
<Link href="/plattform" className={linkClass}>
|
||||
Plattform
|
||||
</Link>
|
||||
<Link href="/profil" className={linkClass}>
|
||||
Mein Profil
|
||||
</Link>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className={layoutClass}>
|
||||
<Link
|
||||
|
|
@ -72,6 +88,11 @@ export function NavLinks({
|
|||
Nutzerverwaltung
|
||||
</Link>
|
||||
)}
|
||||
{kannFirmaVerwalten(role) && (
|
||||
<Link href="/firma" className={linkClass}>
|
||||
Firma
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
href="/profil"
|
||||
className="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"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ export type Profile = {
|
|||
id: string;
|
||||
name: string;
|
||||
role: Role;
|
||||
firma_id: string | null;
|
||||
};
|
||||
|
||||
export type ProfileResult =
|
||||
|
|
@ -25,7 +26,7 @@ export const loadProfile = cache(async (): Promise<ProfileResult> => {
|
|||
|
||||
const { data, error } = await supabase
|
||||
.from("profiles")
|
||||
.select("id, name, role")
|
||||
.select("id, name, role, firma_id")
|
||||
.eq("id", user.id)
|
||||
.single();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,12 @@
|
|||
export type Role = "admin" | "disponent" | "fahrer" | "readonly";
|
||||
export type Role = "admin" | "disponent" | "fahrer" | "readonly" | "superadmin";
|
||||
|
||||
export function istSuperadmin(role: Role): boolean {
|
||||
return role === "superadmin";
|
||||
}
|
||||
|
||||
export function kannFirmaVerwalten(role: Role): boolean {
|
||||
return role === "admin";
|
||||
}
|
||||
|
||||
export function canManageUsers(role: Role): boolean {
|
||||
return role === "admin";
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
import { cache } from "react";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import { loadProfile } from "@/lib/auth/profile";
|
||||
import { ladeFirma, type Firma } from "./queries";
|
||||
|
||||
export const FIRMA_GESPERRT = "Ihre Firma ist deaktiviert oder Ihr Zugang ist keiner Firma zugeordnet.";
|
||||
|
||||
export type EigeneFirmaResult =
|
||||
| { status: "unauthenticated" }
|
||||
| { status: "missing-profile" }
|
||||
| { status: "superadmin" }
|
||||
| { status: "keine-firma" }
|
||||
| { status: "ok"; firma: Firma };
|
||||
|
||||
export const ladeEigeneFirma = cache(async (): Promise<EigeneFirmaResult> => {
|
||||
const profil = await loadProfile();
|
||||
if (profil.status !== "ok") return { status: profil.status };
|
||||
if (profil.profile.role === "superadmin") return { status: "superadmin" };
|
||||
if (!profil.profile.firma_id) return { status: "keine-firma" };
|
||||
const supabase = await createClient();
|
||||
const firma = await ladeFirma(supabase, profil.profile.firma_id);
|
||||
return firma ? { status: "ok", firma } : { status: "keine-firma" };
|
||||
});
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { LOGO_MAX_BYTES, LOGO_SICHERHEITS_HEADER, logoContentType, logoPfad, validateLogo } from "./logo";
|
||||
|
||||
describe("validateLogo", () => {
|
||||
it("akzeptiert PNG, JPG und SVG bis 1 MB", () => {
|
||||
expect(validateLogo({ type: "image/png", size: 1000 })).toEqual({ valid: true, endung: "png" });
|
||||
expect(validateLogo({ type: "image/jpeg", size: LOGO_MAX_BYTES })).toEqual({ valid: true, endung: "jpg" });
|
||||
expect(validateLogo({ type: "image/svg+xml", size: 10 })).toEqual({ valid: true, endung: "svg" });
|
||||
});
|
||||
it("lehnt leere, zu grosse und falsche Dateien ab", () => {
|
||||
expect(validateLogo({ type: "image/png", size: 0 })).toEqual({ valid: false, error: "Bitte eine Datei auswählen." });
|
||||
expect(validateLogo({ type: "image/png", size: LOGO_MAX_BYTES + 1 })).toEqual({
|
||||
valid: false,
|
||||
error: "Das Logo darf höchstens 1 MB groß sein.",
|
||||
});
|
||||
expect(validateLogo({ type: "image/gif", size: 10 })).toEqual({
|
||||
valid: false,
|
||||
error: "Bitte ein PNG-, JPG- oder SVG-Bild hochladen.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("logoPfad / logoContentType", () => {
|
||||
it("baut den Pfad im Firmenordner mit Zeitstempel", () => {
|
||||
expect(logoPfad("f1", "png", 123)).toBe("f1/logo-123.png");
|
||||
});
|
||||
it("leitet den Content-Type aus der Endung ab", () => {
|
||||
expect(logoContentType("f1/logo-1.svg")).toBe("image/svg+xml");
|
||||
expect(logoContentType("f1/logo-1.jpg")).toBe("image/jpeg");
|
||||
expect(logoContentType("f1/logo-1.png")).toBe("image/png");
|
||||
});
|
||||
});
|
||||
|
||||
describe("LOGO_SICHERHEITS_HEADER", () => {
|
||||
it("verhindert Script-Ausfuehrung in direkt geoeffneten SVGs", () => {
|
||||
expect(LOGO_SICHERHEITS_HEADER["Content-Security-Policy"]).toContain("sandbox");
|
||||
expect(LOGO_SICHERHEITS_HEADER["Content-Security-Policy"]).toContain("default-src 'none'");
|
||||
expect(LOGO_SICHERHEITS_HEADER["X-Content-Type-Options"]).toBe("nosniff");
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
export const LOGO_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
export type LogoEndung = "png" | "jpg" | "svg";
|
||||
|
||||
const ENDUNG_NACH_TYP: Record<string, LogoEndung> = {
|
||||
"image/png": "png",
|
||||
"image/jpeg": "jpg",
|
||||
"image/svg+xml": "svg",
|
||||
};
|
||||
|
||||
const TYP_NACH_ENDUNG: Record<LogoEndung, string> = {
|
||||
png: "image/png",
|
||||
jpg: "image/jpeg",
|
||||
svg: "image/svg+xml",
|
||||
};
|
||||
|
||||
export function validateLogo(datei: { type: string; size: number }):
|
||||
| { valid: true; endung: LogoEndung }
|
||||
| { valid: false; error: string } {
|
||||
if (datei.size === 0) return { valid: false, error: "Bitte eine Datei auswählen." };
|
||||
const endung = ENDUNG_NACH_TYP[datei.type];
|
||||
if (!endung) return { valid: false, error: "Bitte ein PNG-, JPG- oder SVG-Bild hochladen." };
|
||||
if (datei.size > LOGO_MAX_BYTES) return { valid: false, error: "Das Logo darf höchstens 1 MB groß sein." };
|
||||
return { valid: true, endung };
|
||||
}
|
||||
|
||||
// Zeitstempel im Namen: ein neues Logo hat eine neue URL und kommt nicht aus dem Cache.
|
||||
export function logoPfad(firmaId: string, endung: LogoEndung, jetzt: number = Date.now()): string {
|
||||
return `${firmaId}/logo-${jetzt}.${endung}`;
|
||||
}
|
||||
|
||||
export function logoContentType(pfad: string): string {
|
||||
const endung = pfad.split(".").pop() as LogoEndung;
|
||||
return TYP_NACH_ENDUNG[endung] ?? "application/octet-stream";
|
||||
}
|
||||
|
||||
// Ein hochgeladenes SVG kann Script enthalten. Als <img> laeuft es nie, direkt
|
||||
// geoeffnet verhindert die Sandbox-CSP die Ausfuehrung im App-Origin.
|
||||
export const LOGO_SICHERHEITS_HEADER = {
|
||||
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
} as const;
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { pruefeFirmenzugang } from "./queries";
|
||||
|
||||
type Antworten = { profil: { role: string; firma_id: string | null } | null; firma: { id: string } | null };
|
||||
|
||||
function fakeClient(a: Antworten): SupabaseClient {
|
||||
return {
|
||||
from(tabelle: string) {
|
||||
const daten = tabelle === "profiles" ? a.profil : a.firma;
|
||||
const kette = {
|
||||
select: () => kette,
|
||||
eq: () => kette,
|
||||
maybeSingle: async () => ({ data: daten, error: null }),
|
||||
};
|
||||
return kette;
|
||||
},
|
||||
} as unknown as SupabaseClient;
|
||||
}
|
||||
|
||||
describe("pruefeFirmenzugang", () => {
|
||||
it("Superadmin", async () => {
|
||||
expect(await pruefeFirmenzugang(fakeClient({ profil: { role: "superadmin", firma_id: null }, firma: null }), "u")).toBe("superadmin");
|
||||
});
|
||||
it("aktive Firma", async () => {
|
||||
expect(await pruefeFirmenzugang(fakeClient({ profil: { role: "fahrer", firma_id: "f" }, firma: { id: "f" } }), "u")).toBe("ok");
|
||||
});
|
||||
it("deaktivierte Firma (RLS liefert keine Zeile)", async () => {
|
||||
expect(await pruefeFirmenzugang(fakeClient({ profil: { role: "fahrer", firma_id: "f" }, firma: null }), "u")).toBe("gesperrt");
|
||||
});
|
||||
it("Nutzer ohne Firma", async () => {
|
||||
expect(await pruefeFirmenzugang(fakeClient({ profil: { role: "readonly", firma_id: null }, firma: null }), "u")).toBe("gesperrt");
|
||||
});
|
||||
it("kein Profil", async () => {
|
||||
expect(await pruefeFirmenzugang(fakeClient({ profil: null, firma: null }), "u")).toBe("gesperrt");
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
|
||||
export const WIDMANN_FIRMA_ID = "00000000-0000-0000-0000-00000000f001";
|
||||
|
||||
export type Firma = {
|
||||
id: string;
|
||||
name: string;
|
||||
logo_pfad: string | null;
|
||||
whatsapp_empfaenger: string | null;
|
||||
farbe_primaer: string | null;
|
||||
farbe_dunkel: string | null;
|
||||
};
|
||||
|
||||
const FIRMA_SELECT = "id, name, logo_pfad, whatsapp_empfaenger, farbe_primaer, farbe_dunkel";
|
||||
|
||||
// Mit dem Nutzer-Client liefert RLS nur die eigene, aktive Firma: null heisst
|
||||
// fremd, deaktiviert oder nicht vorhanden.
|
||||
export async function ladeFirma(client: SupabaseClient, firmaId: string): Promise<Firma | null> {
|
||||
const { data } = await client.from("firmen").select(FIRMA_SELECT).eq("id", firmaId).maybeSingle();
|
||||
return (data as Firma | null) ?? null;
|
||||
}
|
||||
|
||||
export type FirmaBranding = { name: string; logo_pfad: string | null; farbe_primaer: string | null };
|
||||
|
||||
// Firma des Auftrags fuer PDF und Mail. Wirft bei DB-Fehlern (Dispatcher: Retry).
|
||||
export async function ladeFirmaZumAuftrag(client: SupabaseClient, auftragId: string): Promise<FirmaBranding | null> {
|
||||
const { data, error } = await client
|
||||
.from("auftraege")
|
||||
.select("firma:firmen(name, logo_pfad, farbe_primaer)")
|
||||
.eq("id", auftragId)
|
||||
.maybeSingle();
|
||||
if (error) {
|
||||
throw new Error(`Firma zum Auftrag laden fehlgeschlagen: ${error.message}`);
|
||||
}
|
||||
return ((data as { firma: FirmaBranding | null } | null)?.firma ?? null) as FirmaBranding | null;
|
||||
}
|
||||
|
||||
export type Firmenzugang = "ok" | "superadmin" | "gesperrt";
|
||||
|
||||
export async function pruefeFirmenzugang(client: SupabaseClient, userId: string): Promise<Firmenzugang> {
|
||||
const { data: profil } = await client.from("profiles").select("role, firma_id").eq("id", userId).maybeSingle();
|
||||
const p = profil as { role: string; firma_id: string | null } | null;
|
||||
if (!p) return "gesperrt";
|
||||
if (p.role === "superadmin") return "superadmin";
|
||||
if (!p.firma_id) return "gesperrt";
|
||||
const firma = await ladeFirma(client, p.firma_id);
|
||||
return firma ? "ok" : "gesperrt";
|
||||
}
|
||||
Loading…
Reference in New Issue