feat(frontend): Login + Benutzerverwaltung (Modul 1)
/login: Formular gegen AuthProvider (Access-Token im Memory, Refresh per httpOnly-Cookie), Fehlermeldung bei falschen Zugangsdaten. (app)/layout.tsx: geschuetztes Layout, leitet ohne Session zu /login um, Header mit Nutzer-E-Mail + Abmelden. settings/layout.tsx: zusaetzliches Admin-Gate fuer /settings/users. /settings/users: Liste, Anlegen-Dialog (shadcn/Base UI Dialog+Select), Deaktivieren - alles ueber TanStack Query gegen die Users-API. proxy.ts (Next 16 Nachfolger von middleware.ts): optimistische Cookie-Praesenz-Pruefung fuer /login und /settings/*, echte Autorisierung bleibt serverseitig (RolesGuard). Backend-Fixes waehrend Browser-Verifikation gefunden und behoben: - CORS fehlte komplett (app.enableCors, FRONTEND_ORIGIN) - jeder Cross-Origin-Request von :3000 nach :3001 wurde geblockt. - React-StrictMode-Doppel-Effect liess zwei parallele Refresh-Aufrufe laufen; da Refresh-Tokens rotierend/einmalig sind, gewann einer und der andere bekam 401 -> Nutzer flog nach jedem Reload aus der Session. Fix: AbortController im Session-Restore-Effect. - Manifest verwies auf nicht existente PNG-Icons (404); durch public/icon.svg ersetzt. 7 Vitest-Tests (Login-Formular, Users-Liste, JWT-Decode), Lint, Typecheck und Build gruen. Kompletter Flow (Login, Reload-Persistenz, Benutzer anlegen/deaktivieren, Abmelden, Redirect ohne Session) live im Browser gegen den echten Server verifiziert.
This commit is contained in:
1 parent
370102387f
commit
029484f9d5
23 files changed
+758
-10
No files matched your search
@@ -8,3 +8,4 @@ JWT_ACCESS_EXPIRES_IN="15m"
|
|||||||
JWT_REFRESH_EXPIRES_IN="7d"
|
JWT_REFRESH_EXPIRES_IN="7d"
|
||||||
|
|
||||||
PORT=3001
|
PORT=3001
|
||||||
|
FRONTEND_ORIGIN="http://localhost:3000"
|
||||||
@@ -11,6 +11,11 @@ export function configureApp(app: INestApplication): void {
|
|||||||
app.use(helmet());
|
app.use(helmet());
|
||||||
app.use(cookieParser());
|
app.use(cookieParser());
|
||||||
|
|
||||||
|
app.enableCors({
|
||||||
|
origin: process.env.FRONTEND_ORIGIN ?? 'http://localhost:3000',
|
||||||
|
credentials: true,
|
||||||
|
});
|
||||||
|
|
||||||
app.setGlobalPrefix('api', {
|
app.setGlobalPrefix('api', {
|
||||||
exclude: [
|
exclude: [
|
||||||
{ path: 'health', method: RequestMethod.GET },
|
{ path: 'health', method: RequestMethod.GET },
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import type { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
const SESSION_COOKIE = "refreshToken";
|
||||||
|
|
||||||
|
export function proxy(request: NextRequest) {
|
||||||
|
const hasSession = request.cookies.has(SESSION_COOKIE);
|
||||||
|
const { pathname } = request.nextUrl;
|
||||||
|
|
||||||
|
if (pathname.startsWith("/login")) {
|
||||||
|
if (hasSession) {
|
||||||
|
return NextResponse.redirect(new URL("/settings/users", request.url));
|
||||||
|
}
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasSession) {
|
||||||
|
return NextResponse.redirect(new URL("/login", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ["/login", "/settings/:path*"],
|
||||||
|
};
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<rect width="512" height="512" rx="96" fill="#0a0a0a" />
|
||||||
|
<g fill="#f5c518">
|
||||||
|
<rect x="156" y="176" width="200" height="52" rx="10" />
|
||||||
|
<rect x="156" y="242" width="200" height="52" rx="10" />
|
||||||
|
<rect x="156" y="308" width="200" height="52" rx="10" />
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 340 B |
@@ -0,0 +1,42 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ReactNode, useEffect } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useAuth } from "@/lib/auth/auth-context";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
export default function AppLayout({ children }: { children: ReactNode }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const { user, isLoading, logout } = useAuth();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isLoading && !user) {
|
||||||
|
router.replace("/login");
|
||||||
|
}
|
||||||
|
}, [isLoading, user, router]);
|
||||||
|
|
||||||
|
if (isLoading || !user) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen flex-col">
|
||||||
|
<header className="flex items-center justify-between border-b px-4 py-3">
|
||||||
|
<span className="font-semibold">ApiCore</span>
|
||||||
|
<div className="flex items-center gap-3 text-sm">
|
||||||
|
<span className="text-muted-foreground">{user.email}</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
void logout().then(() => router.push("/login"));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Abmelden
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div className="flex-1">{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ReactNode } from "react";
|
||||||
|
import { useAuth } from "@/lib/auth/auth-context";
|
||||||
|
|
||||||
|
export default function SettingsLayout({ children }: { children: ReactNode }) {
|
||||||
|
const { user } = useAuth();
|
||||||
|
|
||||||
|
if (user?.role !== "ADMIN") {
|
||||||
|
return (
|
||||||
|
<main className="p-6">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Diese Seite ist nur für Administratoren verfügbar.
|
||||||
|
</p>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { FormEvent, useState } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { createUser } from "@/lib/users/api";
|
||||||
|
import { Role } from "@/lib/users/types";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
|
||||||
|
const ROLES: Role[] = ["ADMIN", "BEEKEEPER", "STAFF", "READONLY", "API_CLIENT"];
|
||||||
|
|
||||||
|
export function CreateUserDialog() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [role, setRole] = useState<Role>("STAFF");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: createUser,
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||||
|
setOpen(false);
|
||||||
|
setEmail("");
|
||||||
|
setPassword("");
|
||||||
|
setName("");
|
||||||
|
setRole("STAFF");
|
||||||
|
setError(null);
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
setError("Benutzer konnte nicht angelegt werden.");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
mutation.mutate({ email, password, name, role });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogTrigger render={<Button>+ Neuer Benutzer</Button>} />
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Neuen Benutzer anlegen</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="new-user-name">Name</Label>
|
||||||
|
<Input
|
||||||
|
id="new-user-name"
|
||||||
|
required
|
||||||
|
value={name}
|
||||||
|
onChange={(event) => setName(event.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="new-user-email">E-Mail</Label>
|
||||||
|
<Input
|
||||||
|
id="new-user-email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
value={email}
|
||||||
|
onChange={(event) => setEmail(event.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="new-user-password">Passwort</Label>
|
||||||
|
<Input
|
||||||
|
id="new-user-password"
|
||||||
|
type="password"
|
||||||
|
minLength={8}
|
||||||
|
required
|
||||||
|
value={password}
|
||||||
|
onChange={(event) => setPassword(event.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="new-user-role">Rolle</Label>
|
||||||
|
<Select value={role} onValueChange={(value) => setRole(value as Role)}>
|
||||||
|
<SelectTrigger id="new-user-role">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{ROLES.map((roleOption) => (
|
||||||
|
<SelectItem key={roleOption} value={roleOption}>
|
||||||
|
{roleOption}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
{error ? (
|
||||||
|
<p role="alert" className="text-sm text-red-600">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
<DialogFooter>
|
||||||
|
<Button type="submit" disabled={mutation.isPending}>
|
||||||
|
{mutation.isPending ? "Wird angelegt…" : "Anlegen"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import type { ReactElement } from "react";
|
||||||
|
import UsersPage from "./page";
|
||||||
|
import { deactivateUser, fetchUsers } from "@/lib/users/api";
|
||||||
|
|
||||||
|
vi.mock("@/lib/users/api", () => ({
|
||||||
|
fetchUsers: vi.fn(),
|
||||||
|
deactivateUser: vi.fn(),
|
||||||
|
createUser: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
function renderWithClient(ui: ReactElement) {
|
||||||
|
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||||
|
return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("UsersPage", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.mocked(fetchUsers).mockReset();
|
||||||
|
vi.mocked(deactivateUser).mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders the fetched users", async () => {
|
||||||
|
vi.mocked(fetchUsers).mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: "1",
|
||||||
|
email: "[email protected]",
|
||||||
|
name: "Admin",
|
||||||
|
role: "ADMIN",
|
||||||
|
isActive: true,
|
||||||
|
createdAt: "",
|
||||||
|
deactivatedAt: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
renderWithClient(<UsersPage />);
|
||||||
|
|
||||||
|
expect(await screen.findByText("[email protected]")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Aktiv")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows an error message when loading users fails", async () => {
|
||||||
|
vi.mocked(fetchUsers).mockRejectedValueOnce(new Error("boom"));
|
||||||
|
|
||||||
|
renderWithClient(<UsersPage />);
|
||||||
|
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent(/nicht geladen/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { deactivateUser, fetchUsers } from "@/lib/users/api";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/components/ui/table";
|
||||||
|
import { CreateUserDialog } from "./create-user-dialog";
|
||||||
|
|
||||||
|
export default function UsersPage() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { data: users, isLoading, isError } = useQuery({
|
||||||
|
queryKey: ["users"],
|
||||||
|
queryFn: fetchUsers,
|
||||||
|
});
|
||||||
|
|
||||||
|
const deactivateMutation = useMutation({
|
||||||
|
mutationFn: deactivateUser,
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["users"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="flex flex-col gap-4 p-4 sm:p-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h1 className="text-xl font-semibold">Benutzerverwaltung</h1>
|
||||||
|
<CreateUserDialog />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading ? <p className="text-sm text-muted-foreground">Lädt…</p> : null}
|
||||||
|
{isError ? (
|
||||||
|
<p role="alert" className="text-sm text-red-600">
|
||||||
|
Benutzer konnten nicht geladen werden.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{users ? (
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Name</TableHead>
|
||||||
|
<TableHead>E-Mail</TableHead>
|
||||||
|
<TableHead>Rolle</TableHead>
|
||||||
|
<TableHead>Status</TableHead>
|
||||||
|
<TableHead className="text-right">Aktion</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{users.map((user) => (
|
||||||
|
<TableRow key={user.id}>
|
||||||
|
<TableCell>{user.name}</TableCell>
|
||||||
|
<TableCell>{user.email}</TableCell>
|
||||||
|
<TableCell>{user.role}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Badge variant={user.isActive ? "default" : "secondary"}>
|
||||||
|
{user.isActive ? "Aktiv" : "Deaktiviert"}
|
||||||
|
</Badge>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={!user.isActive || deactivateMutation.isPending}
|
||||||
|
onClick={() => deactivateMutation.mutate(user.id)}
|
||||||
|
>
|
||||||
|
Deaktivieren
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
) : null}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import LoginPage from "./page";
|
||||||
|
|
||||||
|
const pushMock = vi.fn();
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
useRouter: () => ({ push: pushMock }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const loginMock = vi.fn();
|
||||||
|
vi.mock("@/lib/auth/auth-context", () => ({
|
||||||
|
useAuth: () => ({ login: loginMock, user: null, isLoading: false, logout: vi.fn() }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("LoginPage", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
pushMock.mockReset();
|
||||||
|
loginMock.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("submits credentials and redirects on success", async () => {
|
||||||
|
loginMock.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(loginMock).toHaveBeenCalledWith("[email protected]", "ChangeMe123!");
|
||||||
|
expect(pushMock).toHaveBeenCalledWith("/settings/users");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows an error message when login fails", async () => {
|
||||||
|
loginMock.mockRejectedValueOnce(new Error("nope"));
|
||||||
|
render(<LoginPage />);
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByLabelText("E-Mail"), "[email protected]");
|
||||||
|
await userEvent.type(screen.getByLabelText("Passwort"), "wrong-password");
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: /anmelden/i }));
|
||||||
|
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent(/fehlgeschlagen/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { FormEvent, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useAuth } from "@/lib/auth/auth-context";
|
||||||
|
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";
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const { login } = useAuth();
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
|
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
setIsSubmitting(true);
|
||||||
|
try {
|
||||||
|
await login(email, password);
|
||||||
|
router.push("/settings/users");
|
||||||
|
} catch {
|
||||||
|
setError("Login fehlgeschlagen. Bitte E-Mail und Passwort prüfen.");
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="flex min-h-screen items-center justify-center bg-zinc-50 p-4 dark:bg-black">
|
||||||
|
<Card className="w-full max-w-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>ApiCore Login</CardTitle>
|
||||||
|
<CardDescription>Digitale Imkereiverwaltung</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-red-600">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
<Button type="submit" disabled={isSubmitting}>
|
||||||
|
{isSubmitting ? "Anmelden…" : "Anmelden"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,14 +11,9 @@ export default function manifest(): MetadataRoute.Manifest {
|
|||||||
theme_color: "#0a0a0a",
|
theme_color: "#0a0a0a",
|
||||||
icons: [
|
icons: [
|
||||||
{
|
{
|
||||||
src: "/icon-192x192.png",
|
src: "/icon.svg",
|
||||||
sizes: "192x192",
|
sizes: "any",
|
||||||
type: "image/png",
|
type: "image/svg+xml",
|
||||||
},
|
|
||||||
{
|
|
||||||
src: "/icon-512x512.png",
|
|
||||||
sizes: "512x512",
|
|
||||||
type: "image/png",
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,9 +2,14 @@
|
|||||||
|
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { AuthProvider } from "@/lib/auth/auth-context";
|
||||||
|
|
||||||
export function Providers({ children }: { children: React.ReactNode }) {
|
export function Providers({ children }: { children: React.ReactNode }) {
|
||||||
const [queryClient] = useState(() => new QueryClient());
|
const [queryClient] = useState(() => new QueryClient());
|
||||||
|
|
||||||
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
|
return (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<AuthProvider>{children}</AuthProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { getAccessToken, setAccessToken } from './token-store';
|
||||||
|
import { refreshRequest } from './api';
|
||||||
|
|
||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001/api/v1';
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
status: number;
|
||||||
|
|
||||||
|
constructor(status: number, message: string) {
|
||||||
|
super(message);
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function rawFetch(path: string, init: RequestInit): Promise<Response> {
|
||||||
|
const token = getAccessToken();
|
||||||
|
return fetch(`${API_URL}${path}`, {
|
||||||
|
...init,
|
||||||
|
credentials: 'include',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||||
|
...init.headers,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||||
|
let response = await rawFetch(path, init);
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
const refreshed = await refreshRequest();
|
||||||
|
if (refreshed) {
|
||||||
|
setAccessToken(refreshed.accessToken);
|
||||||
|
response = await rawFetch(path, init);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const body: unknown = await response.json().catch(() => ({}));
|
||||||
|
const message =
|
||||||
|
typeof body === 'object' && body !== null && 'message' in body
|
||||||
|
? String((body as { message: unknown }).message)
|
||||||
|
: 'Request failed';
|
||||||
|
throw new ApiError(response.status, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 204) {
|
||||||
|
return undefined as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.json() as Promise<T>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001/api/v1';
|
||||||
|
|
||||||
|
export interface AccessTokenResponse {
|
||||||
|
accessToken: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loginRequest(email: string, password: string): Promise<AccessTokenResponse> {
|
||||||
|
const response = await fetch(`${API_URL}/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Login fehlgeschlagen. Bitte E-Mail und Passwort prüfen.');
|
||||||
|
}
|
||||||
|
return response.json() as Promise<AccessTokenResponse>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function refreshRequest(signal?: AbortSignal): Promise<AccessTokenResponse | null> {
|
||||||
|
const response = await fetch(`${API_URL}/auth/refresh`, {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return response.json() as Promise<AccessTokenResponse>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function logoutRequest(): Promise<void> {
|
||||||
|
await fetch(`${API_URL}/auth/logout`, { method: 'POST', credentials: 'include' });
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { createContext, useCallback, useContext, useEffect, useState, ReactNode } from 'react';
|
||||||
|
import { loginRequest, logoutRequest, refreshRequest } from './api';
|
||||||
|
import { decodeAccessToken } from './jwt';
|
||||||
|
import { setAccessToken as storeAccessToken } from './token-store';
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
role: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthContextValue {
|
||||||
|
user: AuthUser | null;
|
||||||
|
isLoading: boolean;
|
||||||
|
login: (email: string, password: string) => Promise<void>;
|
||||||
|
logout: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||||
|
|
||||||
|
function applyAccessToken(token: string): AuthUser | null {
|
||||||
|
storeAccessToken(token);
|
||||||
|
const claims = decodeAccessToken(token);
|
||||||
|
if (!claims) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return { id: claims.sub, email: claims.email, role: claims.role };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [user, setUser] = useState<AuthUser | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
refreshRequest(controller.signal)
|
||||||
|
.then((result) => {
|
||||||
|
if (!result) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setUser(applyAccessToken(result.accessToken));
|
||||||
|
})
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
if (error instanceof DOMException && error.name === "AbortError") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!controller.signal.aborted) {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
controller.abort();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const login = useCallback(async (email: string, password: string) => {
|
||||||
|
const result = await loginRequest(email, password);
|
||||||
|
setUser(applyAccessToken(result.accessToken));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const logout = useCallback(async () => {
|
||||||
|
await logoutRequest();
|
||||||
|
storeAccessToken(null);
|
||||||
|
setUser(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext.Provider value={{ user, isLoading, login, logout }}>
|
||||||
|
{children}
|
||||||
|
</AuthContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuth(): AuthContextValue {
|
||||||
|
const context = useContext(AuthContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useAuth must be used within an AuthProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { decodeAccessToken } from "./jwt";
|
||||||
|
|
||||||
|
function makeToken(payload: object): string {
|
||||||
|
const header = btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }));
|
||||||
|
const body = btoa(JSON.stringify(payload));
|
||||||
|
return `${header}.${body}.signature`;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("decodeAccessToken", () => {
|
||||||
|
it("decodes a valid JWT payload", () => {
|
||||||
|
const token = makeToken({ sub: "user-1", email: "[email protected]", role: "ADMIN", exp: 123 });
|
||||||
|
expect(decodeAccessToken(token)).toEqual({
|
||||||
|
sub: "user-1",
|
||||||
|
email: "[email protected]",
|
||||||
|
role: "ADMIN",
|
||||||
|
exp: 123,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for a malformed token", () => {
|
||||||
|
expect(decodeAccessToken("not-a-jwt")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
export interface AccessTokenClaims {
|
||||||
|
sub: string;
|
||||||
|
email: string;
|
||||||
|
role: string;
|
||||||
|
exp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeAccessToken(token: string): AccessTokenClaims | null {
|
||||||
|
try {
|
||||||
|
const payload = token.split('.')[1];
|
||||||
|
const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
|
const json = atob(base64);
|
||||||
|
return JSON.parse(json) as AccessTokenClaims;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
let currentAccessToken: string | null = null;
|
||||||
|
|
||||||
|
export function getAccessToken(): string | null {
|
||||||
|
return currentAccessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setAccessToken(token: string | null): void {
|
||||||
|
currentAccessToken = token;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { apiFetch } from "@/lib/auth/api-client";
|
||||||
|
import { CreateUserInput, User } from "./types";
|
||||||
|
|
||||||
|
export function fetchUsers(): Promise<User[]> {
|
||||||
|
return apiFetch<User[]>("/users");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createUser(input: CreateUserInput): Promise<User> {
|
||||||
|
return apiFetch<User>("/users", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deactivateUser(id: string): Promise<User> {
|
||||||
|
return apiFetch<User>(`/users/${id}/deactivate`, { method: "POST" });
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
export type Role = "ADMIN" | "BEEKEEPER" | "STAFF" | "READONLY" | "API_CLIENT";
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
name: string;
|
||||||
|
role: Role;
|
||||||
|
isActive: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
deactivatedAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateUserInput {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
name: string;
|
||||||
|
role: Role;
|
||||||
|
}
|
||||||
@@ -19,7 +19,7 @@ Abgeleitet aus [`docs/lastenheft.md`](docs/lastenheft.md) Abschnitt 26. Reihenfo
|
|||||||
- Frontend: `/login`, `/settings/users` (nur Administrator)
|
- Frontend: `/login`, `/settings/users` (nur Administrator)
|
||||||
- [x] Rollen-Enum + Guards (`JwtAuthGuard`, `RolesGuard`, `@Roles()`) implementiert und in jedem künftigen Modul verpflichtend
|
- [x] Rollen-Enum + Guards (`JwtAuthGuard`, `RolesGuard`, `@Roles()`) implementiert und in jedem künftigen Modul verpflichtend
|
||||||
- [x] Backend-Modul fertig, getestet, grün, committet
|
- [x] Backend-Modul fertig, getestet, grün, committet
|
||||||
- [ ] Frontend-Views fertig, getestet, grün, committet
|
- [x] Frontend-Views fertig, getestet, grün, committet
|
||||||
|
|
||||||
### 2. Bienenstände
|
### 2. Bienenstände
|
||||||
|
|
||||||
|
|||||||
@@ -6,3 +6,4 @@ data:
|
|||||||
PORT: "3001"
|
PORT: "3001"
|
||||||
JWT_ACCESS_EXPIRES_IN: "15m"
|
JWT_ACCESS_EXPIRES_IN: "15m"
|
||||||
JWT_REFRESH_EXPIRES_IN: "7d"
|
JWT_REFRESH_EXPIRES_IN: "7d"
|
||||||
|
FRONTEND_ORIGIN: "https://apicore.example.com"
|
||||||
Reference in new issue
Block a user