feat: RBAC Phase 5 - Rollenverwaltung im Frontend
Neue /settings/roles-Seite (Aktiv/Historie, Karten-Grid) zum Anlegen,
Bearbeiten, Deaktivieren und Reaktivieren von Rollen mit einer
Rechte-Matrix (nach Bereich gruppierte Checkboxen, Gruppen-Toggle,
Live-Zaehler), passend zum Backend aus Phase 1-3.
- AuthContext liest Rolle/Rechte jetzt ueber GET /auth/me statt aus
dem JWT (das seit Phase 3 keinen role-Claim mehr traegt); neue
hasPermission()-Hilfsfunktion ersetzt String-Vergleiche gegen "ADMIN".
- Sidebar zeigt Verwaltungs-Eintraege jetzt einzeln nach Berechtigung
(statt Alles-oder-Nichts fuer ADMIN), inkl. neuem "Rollen & Rechte"-
Eintrag.
- Settings-Layout blockt nur noch, wenn gar keine Verwaltungs-
Berechtigung vorhanden ist, statt stur auf die ADMIN-Rolle zu pruefen.
- Benutzerseite: Rollen-Auswahl laedt jetzt aktive Rollen von
GET /roles statt einer festen 5-Werte-Liste; sendet roleId statt
role an POST/PATCH /users.
- Totes jwt.ts (Rolle wurde bislang aus dem Token dekodiert) entfernt.
Live im Browser getestet (Login, Sidebar, Rollen anlegen/bearbeiten/
deaktivieren/reaktivieren, Benutzer-Dialog): dabei einen echten a11y-
Bug gefunden und behoben - Gruppen-Checkboxen fuer mehrwortige
Bereichsnamen ("Wiederkehrende Aufgaben", "Rollen & Rechte") hatten
keinen zugaenglichen Namen, weil die HTML-id ein Leerzeichen enthielt;
jetzt ueber einen Slug erzeugt.
Verifiziert: tsc, lint, build, alle Unit-Tests (14/14) gruen.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
1 parent
ae53f7889e
commit
335c572dfc
17 files changed
+753
-80
No files matched your search
@@ -48,3 +48,23 @@ export function refreshRequest(): Promise<AccessTokenResponse | null> {
|
||||
export async function logoutRequest(): Promise<void> {
|
||||
await fetch(`${API_URL}/auth/logout`, { method: 'POST', credentials: 'include' });
|
||||
}
|
||||
|
||||
export interface CurrentUserProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
roleKey: string;
|
||||
roleName: string;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export async function getCurrentUserRequest(accessToken: string): Promise<CurrentUserProfile> {
|
||||
const response = await fetch(`${API_URL}/auth/me`, {
|
||||
credentials: 'include',
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Profil konnte nicht geladen werden.');
|
||||
}
|
||||
return response.json() as Promise<CurrentUserProfile>;
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useState, ReactNode } from 'react';
|
||||
import { loginRequest, logoutRequest, refreshRequest } from './api';
|
||||
import { decodeAccessToken } from './jwt';
|
||||
import { getCurrentUserRequest, loginRequest, logoutRequest, refreshRequest } from './api';
|
||||
import { setAccessToken as storeAccessToken } from './token-store';
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
name: string;
|
||||
roleKey: string;
|
||||
roleName: string;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
interface AuthContextValue {
|
||||
@@ -16,17 +18,18 @@ interface AuthContextValue {
|
||||
isLoading: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
hasPermission: (permission: string) => boolean;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
function applyAccessToken(token: string): AuthUser | null {
|
||||
async function applyAccessToken(token: string): Promise<AuthUser | null> {
|
||||
storeAccessToken(token);
|
||||
const claims = decodeAccessToken(token);
|
||||
if (!claims) {
|
||||
try {
|
||||
return await getCurrentUserRequest(token);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return { id: claims.sub, email: claims.email, role: claims.role };
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
@@ -35,11 +38,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
refreshRequest()
|
||||
.then((result) => {
|
||||
.then(async (result) => {
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
setUser(applyAccessToken(result.accessToken));
|
||||
setUser(await applyAccessToken(result.accessToken));
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false);
|
||||
@@ -48,7 +51,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
const result = await loginRequest(email, password);
|
||||
setUser(applyAccessToken(result.accessToken));
|
||||
setUser(await applyAccessToken(result.accessToken));
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
@@ -57,8 +60,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
const hasPermission = useCallback(
|
||||
(permission: string) => user?.permissions.includes(permission) ?? false,
|
||||
[user],
|
||||
);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, isLoading, login, logout }}>
|
||||
<AuthContext.Provider value={{ user, isLoading, login, logout, hasPermission }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
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,37 @@
|
||||
import { apiFetch } from "@/lib/auth/api-client";
|
||||
import {
|
||||
CreateRoleInput,
|
||||
PermissionCatalogEntry,
|
||||
RoleSummary,
|
||||
UpdateRoleInput,
|
||||
} from "./types";
|
||||
|
||||
export function fetchRoles(): Promise<RoleSummary[]> {
|
||||
return apiFetch<RoleSummary[]>("/roles");
|
||||
}
|
||||
|
||||
export function fetchPermissionCatalog(): Promise<PermissionCatalogEntry[]> {
|
||||
return apiFetch<PermissionCatalogEntry[]>("/roles/permission-catalog");
|
||||
}
|
||||
|
||||
export function createRole(input: CreateRoleInput): Promise<RoleSummary> {
|
||||
return apiFetch<RoleSummary>("/roles", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function updateRole(id: string, input: UpdateRoleInput): Promise<RoleSummary> {
|
||||
return apiFetch<RoleSummary>(`/roles/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function deactivateRole(id: string): Promise<RoleSummary> {
|
||||
return apiFetch<RoleSummary>(`/roles/${id}/deactivate`, { method: "POST" });
|
||||
}
|
||||
|
||||
export function reactivateRole(id: string): Promise<RoleSummary> {
|
||||
return apiFetch<RoleSummary>(`/roles/${id}/reactivate`, { method: "POST" });
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
export interface PermissionCatalogEntry {
|
||||
key: string;
|
||||
resource: string;
|
||||
action: string;
|
||||
labelDe: string;
|
||||
groupDe: string;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
export type RoleStatus = "ACTIVE" | "INACTIVE";
|
||||
|
||||
export interface RoleSummary {
|
||||
id: string;
|
||||
key: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
isSystem: boolean;
|
||||
status: RoleStatus;
|
||||
userCount: number;
|
||||
permissionKeys: string[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
deactivatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface CreateRoleInput {
|
||||
key: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
permissionKeys: string[];
|
||||
}
|
||||
|
||||
export interface UpdateRoleInput {
|
||||
name?: string;
|
||||
description?: string;
|
||||
permissionKeys?: string[];
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
export type Role = "ADMIN" | "BEEKEEPER" | "STAFF" | "READONLY" | "API_CLIENT";
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: Role;
|
||||
roleId: string;
|
||||
roleKey: string;
|
||||
roleName: string;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
deactivatedAt: string | null;
|
||||
@@ -14,5 +14,10 @@ export interface CreateUserInput {
|
||||
email: string;
|
||||
password: string;
|
||||
name: string;
|
||||
role: Role;
|
||||
roleId: string;
|
||||
}
|
||||
|
||||
export interface UpdateUserInput {
|
||||
name?: string;
|
||||
roleId?: string;
|
||||
}
|
||||
Reference in new issue
Block a user