feat: MFA (TOTP) und Self-Service-Profilseite
Benutzer koennen jetzt selbst Zwei-Faktor-Authentifizierung einrichten
und ihr Profil verwalten (Name, E-Mail, Passwort, Profilbild).
Backend:
- Neues MfaModule (src/auth/mfa/): AES-256-GCM-verschluesselte
TOTP-Secrets (otplib), QR-Code-Erzeugung, kurzlebige Setup-/
Challenge-JWTs fuer den 2-Schritt-Login-Flow
- Neues ProfileModule (src/profile/): PATCH /profile,
POST /profile/password, POST/DELETE/GET /profile/avatar,
POST /profile/mfa/enroll(/confirm), POST /profile/mfa/disable -
alle self-scoped ueber actor.id, ohne @RequirePermission (siehe
ALLOWLIST in authorization-coverage.e2e-spec.ts)
- AuthService.login() zweistufig: bei aktivem MFA erst
{ mfaRequired, mfaToken } statt Tokens, neuer Endpunkt
POST /auth/mfa/verify schliesst den Flow ab
- Admin-Recovery: POST /users/:id/mfa/reset (users:update) fuer
verlorene MFA-Geraete, da es keinen E-Mail-Reset-Flow gibt
Frontend:
- Login-Seite mit zweitem Schritt fuer den TOTP-Code
- Neue Profilseite (/profile, ausserhalb des admin-only
Settings-Bereichs): Profilbild, Name/E-Mail, Passwort, MFA-Ein-/
Ausrichtung mit QR-Code-Dialog
- Header zeigt jetzt Avatar mit Dropdown (Profil/Abmelden) statt
nur E-Mail-Text
- Admin-Users-Tabelle zeigt MFA-Status + Reset-Button
Haertung nach Security-Review (Backend/Frontend-Diff, kein CRITICAL,
mehrere MEDIUM behoben):
- Access-Token wird bei Passwortwechsel sofort ungueltig
(User.passwordChangedAt + JWT-iat-Vergleich in
PermissionResolverService.isTokenValid, vorher isUserActive) statt
erst nach bis zu 15 Minuten
- E-Mail-Aenderung verlangt jetzt aktuelles Passwort
- POST /profile/password und /profile/mfa/disable haben jetzt das
gleiche strikte Throttling wie Login (SENSITIVE_ACTION_THROTTLE)
- Kein stiller leerer Verschluesselungs-Key-Fallback mehr (wirft
jetzt explizit)
Bewusst zurueckgestellt (dokumentiert, kein aktiver Exploit-Pfad):
dedizierter Verschluesselungs-Key fuer MFA-Secrets statt
JWT_ACCESS_SECRET-Ableitung, dedizierte users:mfa-reset-Permission
statt users:update, separate JWT-Secrets pro Token-Zweck.
Verifiziert: tsc/eslint clean, 297/297 Backend- + 31/31
Frontend-Unit-Tests, Build clean auf beiden Projekten. e2e weiterhin
durch bekanntes WSL2/Postgres-Problem blockiert. Unabhaengiges
Security- und Code-Quality-Review durchgefuehrt (0 CRITICAL, 0 HIGH).
This commit is contained in:
1 parent
6776bdfe73
commit
62004483cf
55 files changed
+2876
-129
No files matched your search
@@ -7,7 +7,15 @@ import { Hexagon } from "lucide-react";
|
||||
import { useAuth } from "@/lib/auth/auth-context";
|
||||
import { NotificationBell } from "@/components/notification-bell";
|
||||
import { OfflineSyncBadge } from "@/components/offline-sync-badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { UserAvatar } from "@/components/user-avatar";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Sidebar } from "./sidebar";
|
||||
import { BottomNav } from "./bottom-nav";
|
||||
import { QuickAddMenu } from "./quick-add-menu";
|
||||
@@ -47,18 +55,28 @@ export default function AppLayout({ children }: { children: ReactNode }) {
|
||||
<div className="flex shrink-0 items-center gap-2 text-sm">
|
||||
<OfflineSyncBadge />
|
||||
<NotificationBell />
|
||||
<span className="hidden max-w-40 truncate text-muted-foreground md:inline">
|
||||
{user.email}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void logout().then(() => router.push("/login"));
|
||||
}}
|
||||
>
|
||||
Abmelden
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger className="rounded-full">
|
||||
<UserAvatar name={user.name} hasAvatar={user.hasAvatar} size="sm" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel className="max-w-48 truncate font-normal text-muted-foreground">
|
||||
{user.email}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem render={<Link href="/profile" />}>
|
||||
Profil
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
void logout().then(() => router.push("/login"));
|
||||
}}
|
||||
>
|
||||
Abmelden
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</header>
|
||||
<div className="flex-1 overflow-y-auto pb-16 sm:pb-0">
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactElement } from "react";
|
||||
import { MfaSection } from "./mfa-section";
|
||||
import { confirmMfaEnrollment, disableMfa, enrollMfa } from "@/lib/profile/api";
|
||||
|
||||
vi.mock("@/lib/profile/api", () => ({
|
||||
enrollMfa: vi.fn(),
|
||||
confirmMfaEnrollment: vi.fn(),
|
||||
disableMfa: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderWithClient(ui: ReactElement) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
|
||||
}
|
||||
|
||||
describe("MfaSection", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(enrollMfa).mockReset();
|
||||
vi.mocked(confirmMfaEnrollment).mockReset();
|
||||
vi.mocked(disableMfa).mockReset();
|
||||
});
|
||||
|
||||
it("shows inactive status with an enable button when MFA is off", () => {
|
||||
renderWithClient(<MfaSection mfaEnabled={false} onChanged={vi.fn()} />);
|
||||
expect(screen.getByText("Inaktiv")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Einrichten" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("starts enrollment, shows the QR code, and confirms with a code", async () => {
|
||||
vi.mocked(enrollMfa).mockResolvedValueOnce({
|
||||
secret: "SECRET",
|
||||
qrCodeSvg: "<svg><rect /></svg>",
|
||||
otpauthUri: "otpauth://totp/x",
|
||||
setupToken: "setup-token",
|
||||
});
|
||||
vi.mocked(confirmMfaEnrollment).mockResolvedValueOnce(undefined);
|
||||
const onChanged = vi.fn();
|
||||
renderWithClient(<MfaSection mfaEnabled={false} onChanged={onChanged} />);
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Einrichten" }));
|
||||
await vi.waitFor(() => expect(enrollMfa).toHaveBeenCalled());
|
||||
|
||||
const codeInput = await screen.findByLabelText("Code");
|
||||
await userEvent.type(codeInput, "123456");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Bestätigen" }));
|
||||
|
||||
expect(confirmMfaEnrollment).toHaveBeenCalledWith("setup-token", "123456");
|
||||
await vi.waitFor(() => expect(onChanged).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it("disables MFA after confirming the current password", async () => {
|
||||
vi.mocked(disableMfa).mockResolvedValueOnce(undefined);
|
||||
const onChanged = vi.fn();
|
||||
renderWithClient(<MfaSection mfaEnabled onChanged={onChanged} />);
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Deaktivieren" }));
|
||||
const passwordInput = await screen.findByLabelText("Passwort");
|
||||
await userEvent.type(passwordInput, "correct-password");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Deaktivieren" }));
|
||||
|
||||
expect(disableMfa).toHaveBeenCalledWith("correct-password");
|
||||
await vi.waitFor(() => expect(onChanged).toHaveBeenCalled());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import { ShieldCheck } from "lucide-react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { confirmMfaEnrollment, disableMfa, enrollMfa } from "@/lib/profile/api";
|
||||
import { MfaEnrollment } from "@/lib/profile/types";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
|
||||
function EnrollDialog({ onEnabled }: { onEnabled: () => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [enrollment, setEnrollment] = useState<MfaEnrollment | null>(null);
|
||||
const [code, setCode] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const startMutation = useMutation({
|
||||
mutationFn: enrollMfa,
|
||||
onSuccess: (result) => setEnrollment(result),
|
||||
onError: () => setError("MFA-Einrichtung konnte nicht gestartet werden."),
|
||||
});
|
||||
|
||||
const confirmMutation = useMutation({
|
||||
mutationFn: () => {
|
||||
if (!enrollment) {
|
||||
throw new Error("no enrollment");
|
||||
}
|
||||
return confirmMfaEnrollment(enrollment.setupToken, code);
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success("MFA aktiviert");
|
||||
onEnabled();
|
||||
handleClose();
|
||||
},
|
||||
onError: () => setError("Code ungültig."),
|
||||
});
|
||||
|
||||
function handleTrigger() {
|
||||
setError(null);
|
||||
setEnrollment(null);
|
||||
setCode("");
|
||||
setOpen(true);
|
||||
startMutation.mutate();
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
setOpen(false);
|
||||
setEnrollment(null);
|
||||
setCode("");
|
||||
setError(null);
|
||||
}
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
confirmMutation.mutate();
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(next) => (next ? undefined : handleClose())}>
|
||||
<Button type="button" onClick={handleTrigger}>
|
||||
Einrichten
|
||||
</Button>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>MFA einrichten</DialogTitle>
|
||||
<DialogDescription>
|
||||
QR-Code mit deiner Authenticator-App scannen, dann den angezeigten Code eingeben.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{enrollment ? (
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
||||
<div
|
||||
className="mx-auto [&_svg]:size-48"
|
||||
// Server-generated from a URI we built ourselves (qrcode npm
|
||||
// package), not user input - safe to render directly.
|
||||
dangerouslySetInnerHTML={{ __html: enrollment.qrCodeSvg }}
|
||||
/>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="mfa-code">Code</Label>
|
||||
<Input
|
||||
id="mfa-code"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
required
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={handleClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={confirmMutation.isPending}>
|
||||
{confirmMutation.isPending ? "Prüfe…" : "Bestätigen"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{startMutation.isPending ? "Lädt…" : error}
|
||||
</p>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function DisableDialog({ onDisabled }: { onDisabled: () => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [currentPassword, setCurrentPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const disableMutation = useMutation({
|
||||
mutationFn: () => disableMfa(currentPassword),
|
||||
onSuccess: () => {
|
||||
toast.success("MFA deaktiviert");
|
||||
onDisabled();
|
||||
handleClose();
|
||||
},
|
||||
onError: () => setError("Passwort ist falsch."),
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
setOpen(false);
|
||||
setCurrentPassword("");
|
||||
setError(null);
|
||||
}
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
disableMutation.mutate();
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(next) => (next ? undefined : handleClose())}>
|
||||
<Button type="button" variant="outline" onClick={() => setOpen(true)}>
|
||||
Deaktivieren
|
||||
</Button>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>MFA deaktivieren</DialogTitle>
|
||||
<DialogDescription>Zur Bestätigung aktuelles Passwort eingeben.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="disable-mfa-password">Passwort</Label>
|
||||
<Input
|
||||
id="disable-mfa-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={currentPassword}
|
||||
onChange={(event) => setCurrentPassword(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={handleClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" variant="destructive" disabled={disableMutation.isPending}>
|
||||
{disableMutation.isPending ? "Wird deaktiviert…" : "Deaktivieren"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function MfaSection({
|
||||
mfaEnabled,
|
||||
onChanged,
|
||||
}: {
|
||||
mfaEnabled: boolean;
|
||||
onChanged: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<ShieldCheck className="size-4.5" />
|
||||
Zwei-Faktor-Authentifizierung
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Zusätzlicher Code aus einer Authenticator-App bei jeder Anmeldung.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex items-center justify-between gap-3">
|
||||
<Badge variant={mfaEnabled ? "default" : "secondary"}>
|
||||
{mfaEnabled ? "Aktiv" : "Inaktiv"}
|
||||
</Badge>
|
||||
{mfaEnabled ? (
|
||||
<DisableDialog onDisabled={onChanged} />
|
||||
) : (
|
||||
<EnrollDialog onEnabled={onChanged} />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactElement } from "react";
|
||||
import ProfilePage from "./page";
|
||||
import { updateProfile, changePassword, uploadAvatar } from "@/lib/profile/api";
|
||||
|
||||
vi.mock("@/lib/profile/api", () => ({
|
||||
updateProfile: vi.fn(),
|
||||
changePassword: vi.fn(),
|
||||
uploadAvatar: vi.fn(),
|
||||
deleteAvatar: vi.fn(),
|
||||
fetchAvatarUrl: vi.fn().mockResolvedValue(null),
|
||||
enrollMfa: vi.fn(),
|
||||
confirmMfaEnrollment: vi.fn(),
|
||||
disableMfa: vi.fn(),
|
||||
}));
|
||||
|
||||
const refreshUserMock = vi.fn();
|
||||
const mockUser = {
|
||||
id: "user-1",
|
||||
email: "[email protected]",
|
||||
name: "Existing User",
|
||||
roleKey: "STAFF",
|
||||
roleName: "Mitarbeiter",
|
||||
permissions: [] as string[],
|
||||
mfaEnabled: false,
|
||||
hasAvatar: false,
|
||||
};
|
||||
vi.mock("@/lib/auth/auth-context", () => ({
|
||||
useAuth: () => ({ user: mockUser, refreshUser: refreshUserMock }),
|
||||
}));
|
||||
|
||||
function renderWithClient(ui: ReactElement) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
|
||||
}
|
||||
|
||||
describe("ProfilePage", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(updateProfile).mockReset();
|
||||
vi.mocked(changePassword).mockReset();
|
||||
vi.mocked(uploadAvatar).mockReset();
|
||||
refreshUserMock.mockReset();
|
||||
});
|
||||
|
||||
it("submits the updated name and email", async () => {
|
||||
vi.mocked(updateProfile).mockResolvedValueOnce({
|
||||
id: "user-1",
|
||||
name: "New Name",
|
||||
email: "[email protected]",
|
||||
});
|
||||
renderWithClient(<ProfilePage />);
|
||||
|
||||
const nameInput = screen.getByLabelText("Name");
|
||||
await userEvent.clear(nameInput);
|
||||
await userEvent.type(nameInput, "New Name");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Speichern" }));
|
||||
|
||||
expect(updateProfile).toHaveBeenCalledWith({
|
||||
name: "New Name",
|
||||
email: "[email protected]",
|
||||
});
|
||||
await vi.waitFor(() => expect(refreshUserMock).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it("submits a password change", async () => {
|
||||
vi.mocked(changePassword).mockResolvedValueOnce(undefined);
|
||||
renderWithClient(<ProfilePage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText("Aktuelles Passwort"), "old-password");
|
||||
await userEvent.type(screen.getByLabelText("Neues Passwort"), "new-password123");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Passwort ändern" }));
|
||||
|
||||
expect(changePassword).toHaveBeenCalledWith("old-password", "new-password123");
|
||||
});
|
||||
|
||||
it("uploads a selected avatar file", async () => {
|
||||
vi.mocked(uploadAvatar).mockResolvedValueOnce(undefined);
|
||||
renderWithClient(<ProfilePage />);
|
||||
|
||||
const file = new File(["binary"], "me.jpg", { type: "image/jpeg" });
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
await userEvent.upload(fileInput, file);
|
||||
|
||||
expect(vi.mocked(uploadAvatar).mock.calls[0]?.[0]).toBe(file);
|
||||
await vi.waitFor(() => expect(refreshUserMock).toHaveBeenCalled());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
"use client";
|
||||
|
||||
import { ChangeEvent, FormEvent, useRef, useState } from "react";
|
||||
import { UserRound } from "lucide-react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useAuth } from "@/lib/auth/auth-context";
|
||||
import {
|
||||
changePassword,
|
||||
deleteAvatar,
|
||||
updateProfile,
|
||||
uploadAvatar,
|
||||
} from "@/lib/profile/api";
|
||||
import { PageHeader } from "@/components/page-header";
|
||||
import { UserAvatar } from "@/components/user-avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { MfaSection } from "./mfa-section";
|
||||
|
||||
function AvatarSection() {
|
||||
const { user, refreshUser } = useAuth();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const uploadMutation = useMutation({
|
||||
mutationFn: uploadAvatar,
|
||||
onSuccess: async () => {
|
||||
await refreshUser();
|
||||
toast.success("Profilbild aktualisiert");
|
||||
},
|
||||
onError: () => toast.error("Profilbild konnte nicht hochgeladen werden"),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: deleteAvatar,
|
||||
onSuccess: async () => {
|
||||
await refreshUser();
|
||||
toast.success("Profilbild entfernt");
|
||||
},
|
||||
onError: () => toast.error("Profilbild konnte nicht entfernt werden"),
|
||||
});
|
||||
|
||||
function handleFileChange(event: ChangeEvent<HTMLInputElement>) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = "";
|
||||
if (file) {
|
||||
uploadMutation.mutate(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Profilbild</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex items-center gap-4">
|
||||
<UserAvatar name={user.name} hasAvatar={user.hasAvatar} size="lg" />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={uploadMutation.isPending}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
{uploadMutation.isPending ? "Lädt hoch…" : "Bild wählen"}
|
||||
</Button>
|
||||
{user.hasAvatar ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => deleteMutation.mutate()}
|
||||
>
|
||||
Entfernen
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileInfoSection() {
|
||||
const { user, refreshUser } = useAuth();
|
||||
const [name, setName] = useState(user?.name ?? "");
|
||||
const [email, setEmail] = useState(user?.email ?? "");
|
||||
const [currentPassword, setCurrentPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const emailChanged = email !== user?.email;
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => updateProfile({ name, email, currentPassword: currentPassword || undefined }),
|
||||
onSuccess: async () => {
|
||||
setCurrentPassword("");
|
||||
await refreshUser();
|
||||
toast.success("Profil aktualisiert");
|
||||
},
|
||||
onError: () =>
|
||||
setError(
|
||||
emailChanged
|
||||
? "Speichern fehlgeschlagen. Passwort falsch oder E-Mail schon vergeben."
|
||||
: "Speichern fehlgeschlagen.",
|
||||
),
|
||||
});
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
mutation.mutate();
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Profil</CardTitle>
|
||||
<CardDescription>Name und E-Mail-Adresse</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="profile-name">Name</Label>
|
||||
<Input
|
||||
id="profile-name"
|
||||
required
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="profile-email">E-Mail</Label>
|
||||
<Input
|
||||
id="profile-email"
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{emailChanged ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="profile-current-password">
|
||||
Aktuelles Passwort (zur Bestätigung der neuen E-Mail)
|
||||
</Label>
|
||||
<Input
|
||||
id="profile-current-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={currentPassword}
|
||||
onChange={(event) => setCurrentPassword(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<Button type="submit" className="self-start" disabled={mutation.isPending}>
|
||||
{mutation.isPending ? "Speichert…" : "Speichern"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function PasswordSection() {
|
||||
const [currentPassword, setCurrentPassword] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => changePassword(currentPassword, newPassword),
|
||||
onSuccess: () => {
|
||||
setCurrentPassword("");
|
||||
setNewPassword("");
|
||||
toast.success("Passwort geändert", {
|
||||
description: "Andere angemeldete Geräte wurden abgemeldet.",
|
||||
});
|
||||
},
|
||||
onError: () => setError("Aktuelles Passwort ist falsch."),
|
||||
});
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
mutation.mutate();
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Passwort</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="current-password">Aktuelles Passwort</Label>
|
||||
<Input
|
||||
id="current-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={currentPassword}
|
||||
onChange={(event) => setCurrentPassword(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="new-password">Neues Passwort</Label>
|
||||
<Input
|
||||
id="new-password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
minLength={8}
|
||||
required
|
||||
value={newPassword}
|
||||
onChange={(event) => setNewPassword(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<Button type="submit" className="self-start" disabled={mutation.isPending}>
|
||||
{mutation.isPending ? "Ändert…" : "Passwort ändern"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { user, refreshUser } = useAuth();
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex flex-col gap-4 p-4 sm:p-6">
|
||||
<PageHeader
|
||||
icon={UserRound}
|
||||
title="Mein Profil"
|
||||
description="Persönliche Daten, Passwort und Sicherheit"
|
||||
gradient="var(--gradient-sage)"
|
||||
/>
|
||||
<div className="grid gap-4 sm:max-w-xl">
|
||||
<AvatarSection />
|
||||
<ProfileInfoSection />
|
||||
<PasswordSection />
|
||||
<MfaSection mfaEnabled={user.mfaEnabled} onChanged={() => void refreshUser()} />
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ vi.mock("@/lib/users/api", () => ({
|
||||
deactivateUser: vi.fn(),
|
||||
activateUser: vi.fn(),
|
||||
createUser: vi.fn(),
|
||||
resetUserMfa: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderWithClient(ui: ReactElement) {
|
||||
@@ -35,6 +36,7 @@ describe("UsersPage", () => {
|
||||
isActive: true,
|
||||
createdAt: "",
|
||||
deactivatedAt: null,
|
||||
mfaEnabled: false,
|
||||
},
|
||||
]);
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { Users } from "lucide-react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { activateUser, deactivateUser, fetchUsers } from "@/lib/users/api";
|
||||
import { activateUser, deactivateUser, fetchUsers, resetUserMfa } from "@/lib/users/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { ConfirmDialog } from "@/components/confirm-dialog";
|
||||
@@ -46,6 +46,15 @@ export default function UsersPage() {
|
||||
onError: () => toast.error("Benutzer konnte nicht aktiviert werden"),
|
||||
});
|
||||
|
||||
const resetMfaMutation = useMutation({
|
||||
mutationFn: resetUserMfa,
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||
toast.success("MFA zurückgesetzt");
|
||||
},
|
||||
onError: () => toast.error("MFA konnte nicht zurückgesetzt werden"),
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="flex flex-col gap-4 p-4 sm:p-6">
|
||||
<PageHeader
|
||||
@@ -75,6 +84,7 @@ export default function UsersPage() {
|
||||
<TableHead>E-Mail</TableHead>
|
||||
<TableHead>Rolle</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>MFA</TableHead>
|
||||
<TableHead className="text-right">Aktion</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
@@ -89,28 +99,48 @@ export default function UsersPage() {
|
||||
{user.isActive ? "Aktiv" : "Deaktiviert"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={user.mfaEnabled ? "default" : "outline"}>
|
||||
{user.mfaEnabled ? "Aktiv" : "Inaktiv"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{user.isActive ? (
|
||||
<ConfirmDialog
|
||||
triggerLabel="Deaktivieren"
|
||||
triggerSize="sm"
|
||||
triggerDisabled={deactivateMutation.isPending}
|
||||
title="Benutzer deaktivieren?"
|
||||
description={`„${user.name}“ kann sich danach nicht mehr anmelden. Der Zugang kann jederzeit über „Aktivieren“ wiederhergestellt werden.`}
|
||||
confirmLabel="Deaktivieren"
|
||||
isPending={deactivateMutation.isPending}
|
||||
onConfirm={() => deactivateMutation.mutate(user.id)}
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={activateMutation.isPending}
|
||||
onClick={() => activateMutation.mutate(user.id)}
|
||||
>
|
||||
Aktivieren
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex justify-end gap-2">
|
||||
{user.mfaEnabled ? (
|
||||
<ConfirmDialog
|
||||
triggerLabel="MFA zurücksetzen"
|
||||
triggerVariant="outline"
|
||||
triggerSize="sm"
|
||||
triggerDisabled={resetMfaMutation.isPending}
|
||||
title="MFA zurücksetzen?"
|
||||
description={`„${user.name}“ muss sich beim nächsten Login ohne Zwei-Faktor-Code anmelden und kann MFA im eigenen Profil neu einrichten. Nutze das nur, wenn das Gerät verloren ging.`}
|
||||
confirmLabel="Zurücksetzen"
|
||||
isPending={resetMfaMutation.isPending}
|
||||
onConfirm={() => resetMfaMutation.mutate(user.id)}
|
||||
/>
|
||||
) : null}
|
||||
{user.isActive ? (
|
||||
<ConfirmDialog
|
||||
triggerLabel="Deaktivieren"
|
||||
triggerSize="sm"
|
||||
triggerDisabled={deactivateMutation.isPending}
|
||||
title="Benutzer deaktivieren?"
|
||||
description={`„${user.name}“ kann sich danach nicht mehr anmelden. Der Zugang kann jederzeit über „Aktivieren“ wiederhergestellt werden.`}
|
||||
confirmLabel="Deaktivieren"
|
||||
isPending={deactivateMutation.isPending}
|
||||
onConfirm={() => deactivateMutation.mutate(user.id)}
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={activateMutation.isPending}
|
||||
onClick={() => activateMutation.mutate(user.id)}
|
||||
>
|
||||
Aktivieren
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
|
||||
@@ -9,18 +9,26 @@ vi.mock("next/navigation", () => ({
|
||||
}));
|
||||
|
||||
const loginMock = vi.fn();
|
||||
const verifyMfaMock = vi.fn();
|
||||
vi.mock("@/lib/auth/auth-context", () => ({
|
||||
useAuth: () => ({ login: loginMock, user: null, isLoading: false, logout: vi.fn() }),
|
||||
useAuth: () => ({
|
||||
login: loginMock,
|
||||
verifyMfa: verifyMfaMock,
|
||||
user: null,
|
||||
isLoading: false,
|
||||
logout: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("LoginPage", () => {
|
||||
beforeEach(() => {
|
||||
pushMock.mockReset();
|
||||
loginMock.mockReset();
|
||||
verifyMfaMock.mockReset();
|
||||
});
|
||||
|
||||
it("submits credentials and redirects on success", async () => {
|
||||
loginMock.mockResolvedValueOnce(undefined);
|
||||
loginMock.mockResolvedValueOnce({ mfaRequired: false });
|
||||
render(<LoginPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText("E-Mail"), "[email protected]");
|
||||
@@ -41,4 +49,38 @@ describe("LoginPage", () => {
|
||||
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(/fehlgeschlagen/i);
|
||||
});
|
||||
|
||||
it("shows the code step and verifies MFA when required", async () => {
|
||||
loginMock.mockResolvedValueOnce({ mfaRequired: true, mfaToken: "mfa-token" });
|
||||
verifyMfaMock.mockResolvedValueOnce(undefined);
|
||||
render(<LoginPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText("E-Mail"), "[email protected]");
|
||||
await userEvent.type(screen.getByLabelText("Passwort"), "ChangeMe123!");
|
||||
await userEvent.click(screen.getByRole("button", { name: /anmelden/i }));
|
||||
|
||||
expect(pushMock).not.toHaveBeenCalled();
|
||||
const codeInput = await screen.findByLabelText("Code");
|
||||
await userEvent.type(codeInput, "123456");
|
||||
await userEvent.click(screen.getByRole("button", { name: /bestätigen/i }));
|
||||
|
||||
expect(verifyMfaMock).toHaveBeenCalledWith("mfa-token", "123456");
|
||||
expect(pushMock).toHaveBeenCalledWith("/dashboard");
|
||||
});
|
||||
|
||||
it("shows an error message when the MFA code is invalid", async () => {
|
||||
loginMock.mockResolvedValueOnce({ mfaRequired: true, mfaToken: "mfa-token" });
|
||||
verifyMfaMock.mockRejectedValueOnce(new Error("nope"));
|
||||
render(<LoginPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText("E-Mail"), "[email protected]");
|
||||
await userEvent.type(screen.getByLabelText("Passwort"), "ChangeMe123!");
|
||||
await userEvent.click(screen.getByRole("button", { name: /anmelden/i }));
|
||||
|
||||
const codeInput = await screen.findByLabelText("Code");
|
||||
await userEvent.type(codeInput, "000000");
|
||||
await userEvent.click(screen.getByRole("button", { name: /bestätigen/i }));
|
||||
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(/ungültig/i);
|
||||
});
|
||||
});
|
||||
@@ -18,19 +18,25 @@ import {
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const { login } = useAuth();
|
||||
const { login, verifyMfa } = useAuth();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [code, setCode] = useState("");
|
||||
const [mfaToken, setMfaToken] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
async function handleCredentialsSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await login(email, password);
|
||||
router.push("/dashboard");
|
||||
const result = await login(email, password);
|
||||
if (result.mfaRequired) {
|
||||
setMfaToken(result.mfaToken);
|
||||
} else {
|
||||
router.push("/dashboard");
|
||||
}
|
||||
} catch {
|
||||
setError("Login fehlgeschlagen. Bitte E-Mail und Passwort prüfen.");
|
||||
} finally {
|
||||
@@ -38,6 +44,23 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMfaSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!mfaToken) {
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await verifyMfa(mfaToken, code);
|
||||
router.push("/dashboard");
|
||||
} catch {
|
||||
setError("Code ungültig. Bitte erneut versuchen.");
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background p-4">
|
||||
<HoneycombPattern />
|
||||
@@ -52,41 +75,83 @@ export default function LoginPage() {
|
||||
</span>
|
||||
<CardTitle className="text-lg">ApiCore</CardTitle>
|
||||
</div>
|
||||
<CardDescription>Digitale Imkereiverwaltung für Wabenhain</CardDescription>
|
||||
<CardDescription>
|
||||
{mfaToken
|
||||
? "Code aus deiner Authenticator-App eingeben"
|
||||
: "Digitale Imkereiverwaltung für Wabenhain"}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="email">E-Mail</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="password">Passwort</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "Anmelden…" : "Anmelden"}
|
||||
</Button>
|
||||
</form>
|
||||
{mfaToken ? (
|
||||
<form className="flex flex-col gap-4" onSubmit={handleMfaSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="code">Code</Label>
|
||||
<Input
|
||||
id="code"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
required
|
||||
autoFocus
|
||||
value={code}
|
||||
onChange={(event) => setCode(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "Prüfe…" : "Bestätigen"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setMfaToken(null);
|
||||
setCode("");
|
||||
setError(null);
|
||||
}}
|
||||
>
|
||||
Zurück
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<form className="flex flex-col gap-4" onSubmit={handleCredentialsSubmit}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="email">E-Mail</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="password">Passwort</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "Anmelden…" : "Anmelden"}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { UserAvatar } from "./user-avatar";
|
||||
import { fetchAvatarUrl } from "@/lib/profile/api";
|
||||
|
||||
vi.mock("@/lib/profile/api", () => ({
|
||||
fetchAvatarUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("UserAvatar", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(fetchAvatarUrl).mockReset();
|
||||
});
|
||||
|
||||
it("shows initials and does not fetch when there is no avatar", () => {
|
||||
render(<UserAvatar name="Anna Berger" hasAvatar={false} />);
|
||||
|
||||
expect(screen.getByText("AB")).toBeInTheDocument();
|
||||
expect(fetchAvatarUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fetches the avatar blob when hasAvatar is true", async () => {
|
||||
// base-ui's AvatarImage only swaps in once the browser fires a real
|
||||
// image load event, which jsdom never does for a blob: URL - so this
|
||||
// asserts on our own fetch call, not on what base-ui renders from it.
|
||||
vi.mocked(fetchAvatarUrl).mockResolvedValueOnce("blob:mock-url");
|
||||
render(<UserAvatar name="Anna Berger" hasAvatar />);
|
||||
|
||||
await vi.waitFor(() => expect(fetchAvatarUrl).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { fetchAvatarUrl } from "@/lib/profile/api";
|
||||
|
||||
function initials(name: string): string {
|
||||
return name
|
||||
.split(" ")
|
||||
.filter(Boolean)
|
||||
.slice(0, 2)
|
||||
.map((part) => part[0]?.toUpperCase())
|
||||
.join("");
|
||||
}
|
||||
|
||||
export function UserAvatar({
|
||||
name,
|
||||
hasAvatar,
|
||||
size = "default",
|
||||
}: {
|
||||
name: string;
|
||||
hasAvatar: boolean;
|
||||
size?: "default" | "sm" | "lg";
|
||||
}) {
|
||||
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasAvatar) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
let objectUrl: string | null = null;
|
||||
void fetchAvatarUrl().then((url) => {
|
||||
if (cancelled) {
|
||||
if (url) {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
return;
|
||||
}
|
||||
objectUrl = url;
|
||||
setAvatarUrl(url);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
};
|
||||
}, [hasAvatar]);
|
||||
|
||||
const showImage = hasAvatar && avatarUrl;
|
||||
|
||||
return (
|
||||
<Avatar size={size}>
|
||||
{showImage ? <AvatarImage src={avatarUrl} alt={name} /> : null}
|
||||
<AvatarFallback>{initials(name) || "?"}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,18 @@ export interface AccessTokenResponse {
|
||||
accessToken: string;
|
||||
}
|
||||
|
||||
export async function loginRequest(email: string, password: string): Promise<AccessTokenResponse> {
|
||||
export interface MfaRequiredResponse {
|
||||
mfaRequired: true;
|
||||
mfaToken: string;
|
||||
}
|
||||
|
||||
export type LoginResponse = AccessTokenResponse | MfaRequiredResponse;
|
||||
|
||||
export function isMfaRequired(response: LoginResponse): response is MfaRequiredResponse {
|
||||
return 'mfaRequired' in response && response.mfaRequired;
|
||||
}
|
||||
|
||||
export async function loginRequest(email: string, password: string): Promise<LoginResponse> {
|
||||
const response = await fetch(`${API_URL}/auth/login`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
@@ -14,6 +25,19 @@ export async function loginRequest(email: string, password: string): Promise<Acc
|
||||
if (!response.ok) {
|
||||
throw new Error('Login fehlgeschlagen. Bitte E-Mail und Passwort prüfen.');
|
||||
}
|
||||
return response.json() as Promise<LoginResponse>;
|
||||
}
|
||||
|
||||
export async function verifyMfaRequest(mfaToken: string, code: string): Promise<AccessTokenResponse> {
|
||||
const response = await fetch(`${API_URL}/auth/mfa/verify`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ mfaToken, code }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Code ungültig. Bitte erneut versuchen.');
|
||||
}
|
||||
return response.json() as Promise<AccessTokenResponse>;
|
||||
}
|
||||
|
||||
@@ -56,6 +80,8 @@ export interface CurrentUserProfile {
|
||||
roleKey: string;
|
||||
roleName: string;
|
||||
permissions: string[];
|
||||
mfaEnabled: boolean;
|
||||
hasAvatar: boolean;
|
||||
}
|
||||
|
||||
export async function getCurrentUserRequest(accessToken: string): Promise<CurrentUserProfile> {
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useState, ReactNode } from 'react';
|
||||
import { getCurrentUserRequest, loginRequest, logoutRequest, refreshRequest } from './api';
|
||||
import { setAccessToken as storeAccessToken } from './token-store';
|
||||
import {
|
||||
getCurrentUserRequest,
|
||||
isMfaRequired,
|
||||
loginRequest,
|
||||
logoutRequest,
|
||||
refreshRequest,
|
||||
verifyMfaRequest,
|
||||
} from './api';
|
||||
import { getAccessToken, setAccessToken as storeAccessToken } from './token-store';
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
@@ -11,14 +18,20 @@ export interface AuthUser {
|
||||
roleKey: string;
|
||||
roleName: string;
|
||||
permissions: string[];
|
||||
mfaEnabled: boolean;
|
||||
hasAvatar: boolean;
|
||||
}
|
||||
|
||||
export type LoginOutcome = { mfaRequired: false } | { mfaRequired: true; mfaToken: string };
|
||||
|
||||
interface AuthContextValue {
|
||||
user: AuthUser | null;
|
||||
isLoading: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
login: (email: string, password: string) => Promise<LoginOutcome>;
|
||||
verifyMfa: (mfaToken: string, code: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
hasPermission: (permission: string) => boolean;
|
||||
refreshUser: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
@@ -49,8 +62,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
const login = useCallback(async (email: string, password: string): Promise<LoginOutcome> => {
|
||||
const result = await loginRequest(email, password);
|
||||
if (isMfaRequired(result)) {
|
||||
return { mfaRequired: true, mfaToken: result.mfaToken };
|
||||
}
|
||||
setUser(await applyAccessToken(result.accessToken));
|
||||
return { mfaRequired: false };
|
||||
}, []);
|
||||
|
||||
const verifyMfa = useCallback(async (mfaToken: string, code: string) => {
|
||||
const result = await verifyMfaRequest(mfaToken, code);
|
||||
setUser(await applyAccessToken(result.accessToken));
|
||||
}, []);
|
||||
|
||||
@@ -65,8 +87,21 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
[user],
|
||||
);
|
||||
|
||||
// Re-fetches the profile with the access token already held in memory -
|
||||
// no need to rotate the refresh-token cookie just to reflect a self-edit
|
||||
// (name/email/avatar/MFA change) in the cached user.
|
||||
const refreshUser = useCallback(async () => {
|
||||
const token = getAccessToken();
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
setUser(await applyAccessToken(token));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, isLoading, login, logout, hasPermission }}>
|
||||
<AuthContext.Provider
|
||||
value={{ user, isLoading, login, verifyMfa, logout, hasPermission, refreshUser }}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { apiFetch, apiFetchBlob, apiFetchFormData } from "@/lib/auth/api-client";
|
||||
import { MfaEnrollment, ProfileSummary, UpdateProfileInput } from "./types";
|
||||
|
||||
export function updateProfile(input: UpdateProfileInput): Promise<ProfileSummary> {
|
||||
return apiFetch<ProfileSummary>("/profile", {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function changePassword(currentPassword: string, newPassword: string): Promise<void> {
|
||||
return apiFetch<void>("/profile/password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ currentPassword, newPassword }),
|
||||
});
|
||||
}
|
||||
|
||||
export function uploadAvatar(file: File): Promise<void> {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return apiFetchFormData<void>("/profile/avatar", formData);
|
||||
}
|
||||
|
||||
export function deleteAvatar(): Promise<void> {
|
||||
return apiFetch<void>("/profile/avatar", { method: "DELETE" });
|
||||
}
|
||||
|
||||
// Fetches the avatar as a blob (the endpoint requires the caller's own
|
||||
// Bearer token, so a plain <img src="..."> can't hit it directly) and hands
|
||||
// back an object URL for use as an <img> source. Returns null when the user
|
||||
// has no avatar (404) or the request otherwise fails.
|
||||
export async function fetchAvatarUrl(): Promise<string | null> {
|
||||
try {
|
||||
const { blob } = await apiFetchBlob("/profile/avatar", "avatar");
|
||||
return URL.createObjectURL(blob);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function enrollMfa(): Promise<MfaEnrollment> {
|
||||
return apiFetch<MfaEnrollment>("/profile/mfa/enroll", { method: "POST" });
|
||||
}
|
||||
|
||||
export function confirmMfaEnrollment(setupToken: string, code: string): Promise<void> {
|
||||
return apiFetch<void>("/profile/mfa/enroll/confirm", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ setupToken, code }),
|
||||
});
|
||||
}
|
||||
|
||||
export function disableMfa(currentPassword: string): Promise<void> {
|
||||
return apiFetch<void>("/profile/mfa/disable", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ currentPassword }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export interface ProfileSummary {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface UpdateProfileInput {
|
||||
name?: string;
|
||||
email?: string;
|
||||
/** Required by the backend when email is being changed; ignored otherwise. */
|
||||
currentPassword?: string;
|
||||
}
|
||||
|
||||
export interface MfaEnrollment {
|
||||
secret: string;
|
||||
qrCodeSvg: string;
|
||||
otpauthUri: string;
|
||||
setupToken: string;
|
||||
}
|
||||
@@ -19,3 +19,7 @@ export function deactivateUser(id: string): Promise<User> {
|
||||
export function activateUser(id: string): Promise<User> {
|
||||
return apiFetch<User>(`/users/${id}/activate`, { method: "POST" });
|
||||
}
|
||||
|
||||
export function resetUserMfa(id: string): Promise<User> {
|
||||
return apiFetch<User>(`/users/${id}/mfa/reset`, { method: "POST" });
|
||||
}
|
||||
@@ -8,6 +8,7 @@ export interface User {
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
deactivatedAt: string | null;
|
||||
mfaEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface CreateUserInput {
|
||||
|
||||
Reference in new issue
Block a user