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>
|
||||
))}
|
||||
|
||||
Reference in new issue
Block a user