forked from jappel/leistungsbilanz-ts
Add login-required user management (admin/user roles, Config->Benutzer)
No self-signup: admins create every account in Config -> Benutzer with a typed start password; a forced password change gates first use. Session- cookie auth protects all /api/* routes; /api/users additionally requires the admin role. See docs/authentication.md. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
b50c00c0ac
commit
c56cfb30ad
36 changed files with 4928 additions and 38 deletions
61
src/frontend/components/AuthProvider.tsx
Normal file
61
src/frontend/components/AuthProvider.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"use client";
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||
import { authApi, type AuthUserDto } from "../utils/auth-api";
|
||||
|
||||
type AuthStatus = "loading" | "signed-in" | "signed-out";
|
||||
|
||||
interface AuthContextValue {
|
||||
status: AuthStatus;
|
||||
user: AuthUserDto | undefined;
|
||||
isAdmin: boolean;
|
||||
reload: () => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [status, setStatus] = useState<AuthStatus>("loading");
|
||||
const [user, setUser] = useState<AuthUserDto | undefined>(undefined);
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
try {
|
||||
const current = await authApi.me();
|
||||
setUser(current);
|
||||
setStatus("signed-in");
|
||||
} catch {
|
||||
setUser(undefined);
|
||||
setStatus("signed-out");
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void reload();
|
||||
}, [reload]);
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await authApi.logout();
|
||||
} finally {
|
||||
setUser(undefined);
|
||||
setStatus("signed-out");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{ status, user, isAdmin: user?.role === "admin", reload, 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;
|
||||
}
|
||||
179
src/frontend/components/LoginGate.tsx
Normal file
179
src/frontend/components/LoginGate.tsx
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { authApi } from "../utils/auth-api";
|
||||
import { useAuth } from "./AuthProvider";
|
||||
|
||||
export function LoginGate({ children }: { children: React.ReactNode }) {
|
||||
const { status, user, reload } = useAuth();
|
||||
|
||||
if (status === "loading") {
|
||||
return (
|
||||
<div className="login-gate-screen">
|
||||
<p>Lädt…</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === "signed-out") {
|
||||
return (
|
||||
<div className="login-gate-screen">
|
||||
<LoginForm onSignedIn={reload} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (user?.mustChangePassword) {
|
||||
return (
|
||||
<div className="login-gate-screen">
|
||||
<ForcedPasswordChangeForm onChanged={reload} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function LoginForm({ onSignedIn }: { onSignedIn: () => Promise<void> }) {
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await authApi.login(username, password);
|
||||
await onSignedIn();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Anmeldung fehlgeschlagen.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="login-gate-card card" onSubmit={handleSubmit}>
|
||||
<h1 className="h4 mb-3">Leistungsbilanz</h1>
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor="login-username">
|
||||
Anmeldename
|
||||
</label>
|
||||
<input
|
||||
id="login-username"
|
||||
className="form-control"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
autoFocus
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor="login-password">
|
||||
Passwort
|
||||
</label>
|
||||
<input
|
||||
id="login-password"
|
||||
type="password"
|
||||
className="form-control"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-danger">{error}</p>}
|
||||
<button type="submit" className="btn btn-primary" disabled={submitting}>
|
||||
{submitting ? "Meldet an…" : "Anmelden"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function ForcedPasswordChangeForm({ onChanged }: { onChanged: () => Promise<void> }) {
|
||||
const [currentPassword, setCurrentPassword] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [newPasswordRepeat, setNewPasswordRepeat] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (newPassword !== newPasswordRepeat) {
|
||||
setError("Die beiden neuen Passwörter stimmen nicht überein.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await authApi.changePassword(currentPassword, newPassword);
|
||||
await onChanged();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Passwort konnte nicht geändert werden.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="login-gate-card card" onSubmit={handleSubmit}>
|
||||
<h1 className="h4 mb-3">Neues Passwort setzen</h1>
|
||||
<p className="text-body-secondary">
|
||||
Dieser Zugang wurde mit einem Startpasswort angelegt. Bitte vor der
|
||||
weiteren Nutzung ein eigenes Passwort vergeben.
|
||||
</p>
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor="force-current-password">
|
||||
Aktuelles (Start-)Passwort
|
||||
</label>
|
||||
<input
|
||||
id="force-current-password"
|
||||
type="password"
|
||||
className="form-control"
|
||||
value={currentPassword}
|
||||
onChange={(event) => setCurrentPassword(event.target.value)}
|
||||
autoComplete="current-password"
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor="force-new-password">
|
||||
Neues Passwort
|
||||
</label>
|
||||
<input
|
||||
id="force-new-password"
|
||||
type="password"
|
||||
className="form-control"
|
||||
value={newPassword}
|
||||
onChange={(event) => setNewPassword(event.target.value)}
|
||||
autoComplete="new-password"
|
||||
minLength={8}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor="force-new-password-repeat">
|
||||
Neues Passwort wiederholen
|
||||
</label>
|
||||
<input
|
||||
id="force-new-password-repeat"
|
||||
type="password"
|
||||
className="form-control"
|
||||
value={newPasswordRepeat}
|
||||
onChange={(event) => setNewPasswordRepeat(event.target.value)}
|
||||
autoComplete="new-password"
|
||||
minLength={8}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-danger">{error}</p>}
|
||||
<button type="submit" className="btn btn-primary" disabled={submitting}>
|
||||
{submitting ? "Speichert…" : "Passwort setzen"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ import { useEffect, useState } from "react";
|
|||
import { listProjects } from "../utils/api";
|
||||
import type { ProjectDto } from "../types";
|
||||
import { ThemeToggle } from "./ThemeToggle";
|
||||
import { useAuth } from "./AuthProvider";
|
||||
|
||||
// Anchors on the project overview page (/projects/[id]).
|
||||
const PROJECT_SECTIONS = [
|
||||
|
|
@ -30,6 +31,7 @@ interface SidebarProps {
|
|||
|
||||
export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) {
|
||||
const pathname = usePathname();
|
||||
const { user, isAdmin, logout } = useAuth();
|
||||
const projectMatch = pathname?.match(PROJECT_PATH_PATTERN);
|
||||
const activeProjectId = projectMatch ? projectMatch[1] : null;
|
||||
const projectSubPath = projectMatch?.[2] ?? "";
|
||||
|
|
@ -179,8 +181,31 @@ export function Sidebar({ isCollapsed, onToggleCollapsed }: SidebarProps) {
|
|||
</>
|
||||
)}
|
||||
</nav>
|
||||
{isAdmin && (
|
||||
<nav className="sidebar-nav sidebar-nav-bottom">
|
||||
<Link
|
||||
href="/config"
|
||||
className={pathname?.startsWith("/config") ? "sidebar-link active" : "sidebar-link"}
|
||||
title="Config"
|
||||
>
|
||||
<span className="sidebar-icon">⚙</span>
|
||||
<span className="sidebar-label">Config</span>
|
||||
</Link>
|
||||
</nav>
|
||||
)}
|
||||
<div className="sidebar-footer">
|
||||
{user && !isCollapsed && (
|
||||
<div className="sidebar-identity" title={`Angemeldet als ${user.name}`}>
|
||||
<span className="sidebar-identity-label">Angemeldet als</span>
|
||||
<span className="sidebar-identity-name">{user.name}</span>
|
||||
</div>
|
||||
)}
|
||||
<ThemeToggle />
|
||||
{user && (
|
||||
<button type="button" className="sidebar-logout" onClick={() => void logout()}>
|
||||
{isCollapsed ? "⏻" : "Abmelden"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
|
|
|
|||
86
src/frontend/utils/auth-api.ts
Normal file
86
src/frontend/utils/auth-api.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
// Small, self-contained fetch helper for the auth/user endpoints - kept
|
||||
// separate from the large domain api.ts so this feature doesn't have to
|
||||
// touch that file's shared `request()` internals.
|
||||
|
||||
export type UserRole = "admin" | "user";
|
||||
|
||||
export interface AuthStatusDto {
|
||||
signedIn: boolean;
|
||||
mustChangePassword: boolean;
|
||||
}
|
||||
|
||||
export interface AuthUserDto {
|
||||
id: string;
|
||||
username: string;
|
||||
name: string;
|
||||
role: UserRole;
|
||||
mustChangePassword: boolean;
|
||||
}
|
||||
|
||||
export interface UserDto {
|
||||
id: string;
|
||||
username: string;
|
||||
name: string;
|
||||
role: UserRole;
|
||||
active: boolean;
|
||||
mustChangePassword: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export class AuthApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
headers: { "Content-Type": "application/json", ...init?.headers },
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok) {
|
||||
let message = `Anfrage fehlgeschlagen (Status ${response.status})`;
|
||||
try {
|
||||
const body = (await response.json()) as { error?: unknown };
|
||||
if (typeof body.error === "string") message = body.error;
|
||||
} catch {
|
||||
// Keep the generic message for non-JSON error responses.
|
||||
}
|
||||
throw new AuthApiError(message, response.status);
|
||||
}
|
||||
if (response.status === 204) return undefined as T;
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
status: () => request<AuthStatusDto>("/api/auth/status"),
|
||||
login: (username: string, password: string) =>
|
||||
request<AuthStatusDto>("/api/auth/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ username, password }),
|
||||
}),
|
||||
me: () => request<AuthUserDto>("/api/auth/me"),
|
||||
changePassword: (currentPassword: string, newPassword: string) =>
|
||||
request<{ changed: true }>("/api/auth/change-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ currentPassword, newPassword }),
|
||||
}),
|
||||
logout: () => request<{ signedOut: true }>("/api/auth/logout", { method: "POST" }),
|
||||
};
|
||||
|
||||
export const userApi = {
|
||||
list: () => request<UserDto[]>("/api/users"),
|
||||
create: (input: { username: string; name: string; role: UserRole; initialPassword: string }) =>
|
||||
request<UserDto>("/api/users", { method: "POST", body: JSON.stringify(input) }),
|
||||
update: (userId: string, patch: { role?: UserRole; active?: boolean }) =>
|
||||
request<UserDto>(`/api/users/${userId}`, { method: "PATCH", body: JSON.stringify(patch) }),
|
||||
resetPassword: (userId: string, newPassword: string) =>
|
||||
request<UserDto>(`/api/users/${userId}/reset-password`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ newPassword }),
|
||||
}),
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue