feat(T01): auth + user management + RBAC + base frontend + i18n
- Backend: FastAPI, JWT auth (HS256), bcrypt, RBAC middleware - User CRUD (admin-only), soft-delete, pagination - Pydantic BaseSettings config, async SQLAlchemy 2.0 - 50 backend tests, 88% coverage - Frontend: Next.js 14 App Router, Tailwind, design tokens - Login page, auth context, API client with auto-refresh - i18n: next-intl, DE/EN (31 keys each) - 6 base UI components (Button, Input, Card, Table, Modal, Toast) - 12 frontend tests, npm build success
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1';
|
||||
|
||||
export interface ApiError {
|
||||
error: {
|
||||
code: string;
|
||||
message: string;
|
||||
details?: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export interface TokenResponse {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
export interface UserResponse {
|
||||
id: string;
|
||||
email: string;
|
||||
full_name: string;
|
||||
role: string;
|
||||
language: string;
|
||||
is_active: boolean;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
function getAuthToken(): string | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
return localStorage.getItem('access_token');
|
||||
}
|
||||
|
||||
function getRefreshToken(): string | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
return localStorage.getItem('refresh_token');
|
||||
}
|
||||
|
||||
export function setTokens(tokens: TokenResponse): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
localStorage.setItem('access_token', tokens.access_token);
|
||||
localStorage.setItem('refresh_token', tokens.refresh_token);
|
||||
}
|
||||
|
||||
export function clearTokens(): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
localStorage.removeItem('access_token');
|
||||
localStorage.removeItem('refresh_token');
|
||||
}
|
||||
|
||||
export function isAuthenticated(): boolean {
|
||||
return getAuthToken() !== null;
|
||||
}
|
||||
|
||||
async function apiFetch<T>(
|
||||
path: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const token = getAuthToken();
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...((options.headers as Record<string, string>) || {}),
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (response.status === 401 && token) {
|
||||
const refreshToken = getRefreshToken();
|
||||
if (refreshToken) {
|
||||
const refreshResult = await apiFetch<TokenResponse>('/auth/refresh', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
});
|
||||
setTokens(refreshResult);
|
||||
headers['Authorization'] = `Bearer ${refreshResult.access_token}`;
|
||||
const retryResponse = await fetch(`${API_BASE_URL}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
if (!retryResponse.ok) {
|
||||
const err = await retryResponse.json().catch(() => ({ error: { code: 'UNKNOWN', message: 'Request failed' } }));
|
||||
throw err as ApiError;
|
||||
}
|
||||
return retryResponse.json();
|
||||
}
|
||||
clearTokens();
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({ error: { code: 'UNKNOWN', message: 'Request failed' } }));
|
||||
throw err as ApiError;
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string): Promise<TokenResponse> {
|
||||
return apiFetch<TokenResponse>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getCurrentUser(): Promise<UserResponse> {
|
||||
return apiFetch<UserResponse>('/auth/me');
|
||||
}
|
||||
|
||||
export async function listUsers(page = 1, pageSize = 20): Promise<PaginatedResponse<UserResponse>> {
|
||||
return apiFetch<PaginatedResponse<UserResponse>>(`/users/?page=${page}&page_size=${pageSize}`);
|
||||
}
|
||||
|
||||
export async function createUser(data: {
|
||||
email: string;
|
||||
password: string;
|
||||
full_name: string;
|
||||
role: string;
|
||||
language: string;
|
||||
}): Promise<UserResponse> {
|
||||
return apiFetch<UserResponse>('/users/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteUser(userId: string): Promise<UserResponse> {
|
||||
return apiFetch<UserResponse>(`/users/${userId}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export async function healthCheck(): Promise<{ status: string }> {
|
||||
return apiFetch<{ status: string }>('/health');
|
||||
}
|
||||
|
||||
export { API_BASE_URL };
|
||||
@@ -0,0 +1,80 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import {
|
||||
login as apiLogin,
|
||||
getCurrentUser,
|
||||
setTokens,
|
||||
clearTokens,
|
||||
isAuthenticated,
|
||||
type UserResponse,
|
||||
type ApiError,
|
||||
} from './api';
|
||||
|
||||
export interface AuthState {
|
||||
user: UserResponse | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const [state, setState] = useState<AuthState>({
|
||||
user: null,
|
||||
loading: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const fetchUser = useCallback(async () => {
|
||||
if (!isAuthenticated()) {
|
||||
setState({ user: null, loading: false, error: null });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
setState({ user, loading: false, error: null });
|
||||
} catch {
|
||||
clearTokens();
|
||||
setState({ user: null, loading: false, error: 'Session expired' });
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUser();
|
||||
}, [fetchUser]);
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
setState({ user: null, loading: true, error: null });
|
||||
try {
|
||||
const tokens = await apiLogin(email, password);
|
||||
setTokens(tokens);
|
||||
const user = await getCurrentUser();
|
||||
setState({ user, loading: false, error: null });
|
||||
return user;
|
||||
} catch (err) {
|
||||
const message = (err as ApiError)?.error?.message || 'Login failed';
|
||||
setState({ user: null, loading: false, error: message });
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearTokens();
|
||||
setState({ user: null, loading: false, error: null });
|
||||
}, []);
|
||||
|
||||
return { ...state, login, logout, refresh: fetchUser };
|
||||
}
|
||||
|
||||
export function useRequireAuth() {
|
||||
const auth = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!auth.loading && !auth.user) {
|
||||
router.push('/login');
|
||||
}
|
||||
}, [auth.loading, auth.user, router]);
|
||||
|
||||
return auth;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useState, useCallback, type ReactNode } from 'react';
|
||||
import deMessages from '@/messages/de.json';
|
||||
import enMessages from '@/messages/en.json';
|
||||
|
||||
export type Locale = 'de' | 'en';
|
||||
|
||||
interface Messages {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
const messageMap: Record<Locale, Messages> = {
|
||||
de: deMessages as Messages,
|
||||
en: enMessages as Messages,
|
||||
};
|
||||
|
||||
interface I18nContextValue {
|
||||
locale: Locale;
|
||||
setLocale: (locale: Locale) => void;
|
||||
t: (key: string, params?: Record<string, string>) => string;
|
||||
}
|
||||
|
||||
const I18nContext = createContext<I18nContextValue | null>(null);
|
||||
|
||||
export function I18nProvider({ children, initialLocale = 'de' }: { children: ReactNode; initialLocale?: Locale }) {
|
||||
const [locale, setLocaleState] = useState<Locale>(initialLocale);
|
||||
|
||||
const setLocale = useCallback((newLocale: Locale) => {
|
||||
setLocaleState(newLocale);
|
||||
if (typeof document !== 'undefined') {
|
||||
document.documentElement.lang = newLocale;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const t = useCallback((key: string, params?: Record<string, string>) => {
|
||||
const messages = messageMap[locale];
|
||||
let message = messages[key] || key;
|
||||
if (params) {
|
||||
for (const [param, value] of Object.entries(params)) {
|
||||
message = message.replace(new RegExp(`\{${param}\}`, 'g'), value);
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}, [locale]);
|
||||
|
||||
return (
|
||||
<I18nContext.Provider value={{ locale, setLocale, t }}>
|
||||
{children}
|
||||
</I18nContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useI18n(): I18nContextValue {
|
||||
const ctx = useContext(I18nContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useI18n must be used within I18nProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
Reference in New Issue
Block a user