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