Phase 7: Frontend auth — React Router, AuthContext, Login/Register, API client

This commit is contained in:
Suslov-MD
2026-08-16 08:54:31 +00:00
parent 281daa4717
commit ac85d71c65
16 changed files with 578 additions and 3 deletions
+2
View File
@@ -95,6 +95,8 @@ export default defineConfig(
'react/no-unstable-nested-components': ['error', { allowAsProps: false }], 'react/no-unstable-nested-components': ['error', { allowAsProps: false }],
/* В TS prop-types не нужны */ /* В TS prop-types не нужны */
'react/prop-types': 'off', 'react/prop-types': 'off',
/* React 18 с jsx: react-jsx не требует React в scope */
'react/react-in-jsx-scope': 'off',
}, },
}, },
+27
View File
@@ -0,0 +1,27 @@
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { AuthProvider } from './auth/AuthContext.js';
import { ProtectedRoute } from './components/ProtectedRoute.js';
import { HomePage } from './pages/HomePage.js';
import { LoginPage } from './pages/LoginPage.js';
import { RegisterPage } from './pages/RegisterPage.js';
/**
* Корневой компонент приложения с роутингом.
*/
export function App() {
return (
<AuthProvider>
<BrowserRouter>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route element={<ProtectedRoute />}>
<Route path="/" element={<HomePage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
</AuthProvider>
);
}
+133
View File
@@ -0,0 +1,133 @@
/**
* API-клиент: fetch-обёртка с автоматическим Authorization header
* и обработкой 401 (logout при истёкшем токене).
*/
/**
* Безопасное извлечение env-переменной Vite.
*/
function getEnvVar(name: string): string {
const val: unknown = (import.meta.env as Record<string, unknown>)[name];
return typeof val === 'string' ? val : '';
}
/** Базовый URL API (через Vite proxy в dev). */
const API_BASE: string = getEnvVar('VITE_API_URL');
/**
* Текущий токен (хранится в localStorage, обновляется AuthContext).
*/
let authToken: string | null = localStorage.getItem('token');
/**
* Устанавливает токен для последующих запросов.
*
* @param token — JWT-токен или null для очистки
*/
export function setAuthToken(token: string | null): void {
authToken = token;
if (token !== null) {
localStorage.setItem('token', token);
} else {
localStorage.removeItem('token');
}
}
/**
* Кастомная ошибка API с кодом и сообщением.
*/
export class ApiClientError extends Error {
/** HTTP статус-код. */
readonly status: number;
/** Код ошибки от backend. */
readonly code: string;
constructor(status: number, code: string, message: string) {
super(message);
this.name = 'ApiClientError';
this.status = status;
this.code = code;
}
}
/**
* Структура error body от backend.
*/
interface ApiErrorBody {
error?: { code?: string; message?: string };
}
/**
* Добавляет Authorization header если токен есть.
*/
function buildHeaders(extra?: Record<string, string>): Record<string, string> {
const headers: Record<string, string> = { ...extra };
if (authToken !== null) {
headers.Authorization = `Bearer ${authToken}`;
}
return headers;
}
/**
* Обрабатывает ответ: при 401 очищает токен, при !ok бросает ApiClientError.
*
* @param res — Response из fetch
* @returns распарсенный JSON
*/
async function handleResponse<T>(res: Response): Promise<T> {
if (res.status === 401 && authToken !== null) {
setAuthToken(null);
window.location.href = '/login';
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- fetch.json() returns any
const data = (await res.json().catch(() => ({}))) as unknown as ApiErrorBody & T;
if (!res.ok) {
throw new ApiClientError(
res.status,
data.error?.code ?? 'UNKNOWN',
data.error?.message ?? res.statusText,
);
}
return data;
}
/**
* Выполняет fetch-запрос к API с авторизацией.
*
* @param path — путь относительно /api (например '/auth/login')
* @param options — параметры fetch (method, body, headers)
* @returns распарсенный JSON
* @throws ApiClientError при статусе >= 400
*/
export async function apiFetch<T>(
path: string,
options: RequestInit = {},
): Promise<T> {
const extraHeaders: Record<string, string> = { 'Content-Type': 'application/json' };
if (options.headers) {
Object.assign(extraHeaders, options.headers);
}
const headers = buildHeaders(extraHeaders);
const res = await fetch(`${API_BASE}/api${path}`, { ...options, headers });
return handleResponse<T>(res);
}
/**
* Выполняет multipart/form-data запрос (для загрузки файлов).
*
* @param path — путь относительно /api
* @param formData — FormData объект
* @returns распарсенный JSON
*/
export async function apiUpload<T>(path: string, formData: FormData): Promise<T> {
const headers = buildHeaders();
const res = await fetch(`${API_BASE}/api${path}`, {
method: 'POST',
headers,
body: formData,
});
return handleResponse<T>(res);
}
+9
View File
@@ -0,0 +1,9 @@
/**
* Типы для API-ответов авторизации.
*/
/** Ответ на регистрацию/логин. */
export interface AuthResponse {
token: string;
user: { id: string; email: string };
}
+98
View File
@@ -0,0 +1,98 @@
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';
import { apiFetch, setAuthToken } from '../api/client.js';
import type { AuthResponse } from '../api/types.js';
/**
* Состояние AuthContext.
*/
interface AuthContextValue {
/** JWT-токен текущего пользователя. */
token: string | null;
/** ID текущего пользователя. */
userId: string | null;
/** Email текущего пользователя. */
userEmail: string | null;
/** true если пользователь авторизован. */
isAuthenticated: boolean;
/**
* Авторизация: login или register.
* @param email — email
* @param password — пароль
* @param isRegister — true для регистрации, false для логина
*/
login: (email: string, password: string) => Promise<void>;
register: (email: string, password: string) => Promise<void>;
logout: () => void;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
/**
* Провайдер авторизации. Хранит token/userId в состоянии + localStorage.
*/
export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
const [userId, setUserId] = useState<string | null>(() => localStorage.getItem('userId'));
const [userEmail, setUserEmail] = useState<string | null>(() => localStorage.getItem('userEmail'));
const handleAuth = useCallback((response: AuthResponse) => {
setAuthToken(response.token);
setToken(response.token);
setUserId(response.user.id);
setUserEmail(response.user.email);
localStorage.setItem('userId', response.user.id);
localStorage.setItem('userEmail', response.user.email);
}, []);
const login = useCallback(async (email: string, password: string) => {
const res = await apiFetch<AuthResponse>('/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password }),
});
handleAuth(res);
}, [handleAuth]);
const register = useCallback(async (email: string, password: string) => {
const res = await apiFetch<AuthResponse>('/auth/register', {
method: 'POST',
body: JSON.stringify({ email, password }),
});
handleAuth(res);
}, [handleAuth]);
const logout = useCallback(() => {
setAuthToken(null);
setToken(null);
setUserId(null);
setUserEmail(null);
localStorage.removeItem('userId');
localStorage.removeItem('userEmail');
}, []);
const value = useMemo<AuthContextValue>(() => ({
token,
userId,
userEmail,
isAuthenticated: token !== null,
login,
register,
logout,
}), [token, userId, userEmail, login, register, logout]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
/**
* Хук доступа к AuthContext.
*
* @throws если вне AuthProvider
*/
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (!ctx) {
throw new Error('useAuth must be used within AuthProvider');
}
return ctx;
}
+16
View File
@@ -0,0 +1,16 @@
import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js';
/**
* Защищённый маршрут: перенаправляет на /login если нет авторизации.
*/
export function ProtectedRoute() {
const { isAuthenticated } = useAuth();
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return <Outlet />;
}
+9
View File
@@ -0,0 +1,9 @@
import { createRoot } from 'react-dom/client';
import { App } from './App.js';
import './styles/global.scss';
const root = document.getElementById('root');
if (root) {
createRoot(root).render(<App />);
}
+19
View File
@@ -0,0 +1,19 @@
import { useAuth } from '../auth/AuthContext.js';
/**
* Главная страница (защитена ProtectedRoute).
* Показывает email пользователя и кнопку logout.
*/
export function HomePage() {
const { userEmail, logout } = useAuth();
return (
<div className="home-page">
<h1>News Editor</h1>
<p>Добро пожаловать, {userEmail}!</p>
<button type="button" onClick={logout}>
Выйти
</button>
</div>
);
}
+68
View File
@@ -0,0 +1,68 @@
import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js';
/**
* Страница логина.
*/
export function LoginPage() {
const { login } = useAuth();
const navigate = useNavigate();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
/* eslint-disable @typescript-eslint/no-floating-promises -- Promise обработан через .catch() */
const handleSubmit = (e: FormEvent): void => {
e.preventDefault();
setError('');
setLoading(true);
login(email, password)
.then(() => { navigate('/'); })
.catch((err: unknown) => {
setError(err instanceof Error ? err.message : 'Ошибка логина');
})
.finally(() => { setLoading(false); });
};
/* eslint-enable @typescript-eslint/no-floating-promises */
return (
<div className="auth-page">
<h1>Вход</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => { setEmail(e.target.value); }}
required
autoComplete="email"
/>
</div>
<div className="form-group">
<label htmlFor="password">Пароль</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => { setPassword(e.target.value); }}
required
autoComplete="current-password"
/>
</div>
{error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={loading}>
{loading ? 'Вход...' : 'Войти'}
</button>
</form>
<p>
Нет аккаунта?{' '}
<a href="/register">Зарегистрироваться</a>
</p>
</div>
);
}
+85
View File
@@ -0,0 +1,85 @@
import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js';
/**
* Страница регистрации.
*/
export function RegisterPage() {
const { register } = useAuth();
const navigate = useNavigate();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
/* eslint-disable @typescript-eslint/no-floating-promises -- Promise обработан через .catch() */
const handleSubmit = (e: FormEvent): void => {
e.preventDefault();
if (password !== confirmPassword) {
setError('Пароли не совпадают');
return;
}
setError('');
setLoading(true);
register(email, password)
.then(() => { navigate('/'); })
.catch((err: unknown) => {
setError(err instanceof Error ? err.message : 'Ошибка регистрации');
})
.finally(() => { setLoading(false); });
};
/* eslint-enable @typescript-eslint/no-floating-promises */
return (
<div className="auth-page">
<h1>Регистрация</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => { setEmail(e.target.value); }}
required
autoComplete="email"
/>
</div>
<div className="form-group">
<label htmlFor="password">Пароль</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => { setPassword(e.target.value); }}
required
minLength={6}
autoComplete="new-password"
/>
</div>
<div className="form-group">
<label htmlFor="confirmPassword">Повторите пароль</label>
<input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => { setConfirmPassword(e.target.value); }}
required
autoComplete="new-password"
/>
</div>
{error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={loading}>
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
</button>
</form>
<p>
Уже есть аккаунт?{' '}
<a href="/login">Войти</a>
</p>
</div>
);
}
+100
View File
@@ -0,0 +1,100 @@
// Глобальные стили News Editor
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
color: #1a1a2e;
background: #f5f5f5;
}
a {
color: #2563eb;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
h1 {
margin-bottom: 1rem;
font-size: 1.8rem;
}
button {
padding: 0.5rem 1.2rem;
border: none;
border-radius: 6px;
background: #2563eb;
color: #fff;
font-size: 0.95rem;
cursor: pointer;
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
&:hover:not(:disabled) {
background: #1d4ed8;
}
}
input {
width: 100%;
padding: 0.5rem 0.75rem;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 0.95rem;
&:focus {
outline: none;
border-color: #2563eb;
box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15);
}
}
// Страница авторизации
.auth-page {
max-width: 400px;
margin: 4rem auto;
padding: 2rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.form-group {
margin-bottom: 1rem;
label {
display: block;
margin-bottom: 0.25rem;
font-weight: 500;
font-size: 0.9rem;
}
}
.error {
color: #dc2626;
font-size: 0.9rem;
margin-bottom: 0.75rem;
}
// Главная страница
.home-page {
max-width: 600px;
margin: 4rem auto;
padding: 2rem;
text-align: center;
p {
margin-bottom: 1.5rem;
}
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+6
View File
@@ -9,6 +9,12 @@ import react from '@vitejs/plugin-react';
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
server: { server: {
host: true,
port: 5173, port: 5173,
proxy: {
'/api': 'http://localhost:3000',
'/uploads': 'http://localhost:3000',
'/socket.io': { target: 'http://localhost:3000', ws: true },
},
}, },
}); });
+2 -2
View File
@@ -27,8 +27,8 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
// Security headers // Security headers
app.use(helmet()); app.use(helmet());
// CORS — whitelist из CLIENT_ORIGIN // CORS — whitelist из CLIENT_ORIGIN (поддерживается несколько через запятую)
app.use(cors({ origin: env.clientOrigin })); app.use(cors({ origin: env.clientOrigins }));
// Парсинг тела запроса // Парсинг тела запроса
app.use(json()); app.use(json());
+2
View File
@@ -36,6 +36,7 @@ export interface Env {
readonly jwtSecret: string; readonly jwtSecret: string;
readonly jwtExpiresIn: string; readonly jwtExpiresIn: string;
readonly clientOrigin: string; readonly clientOrigin: string;
readonly clientOrigins: string[];
readonly uploadDir: string; readonly uploadDir: string;
readonly maxUploadSize: number; readonly maxUploadSize: number;
readonly schedulerIntervalMs: number; readonly schedulerIntervalMs: number;
@@ -105,6 +106,7 @@ export function loadEnv(): Env {
jwtSecret: required('JWT_SECRET'), jwtSecret: required('JWT_SECRET'),
jwtExpiresIn: process.env.JWT_EXPIRES_IN ?? '7d', jwtExpiresIn: process.env.JWT_EXPIRES_IN ?? '7d',
clientOrigin: process.env.CLIENT_ORIGIN ?? 'http://localhost:5173', clientOrigin: process.env.CLIENT_ORIGIN ?? 'http://localhost:5173',
clientOrigins: (process.env.CLIENT_ORIGIN ?? 'http://localhost:5173').split(',').map((s) => s.trim()),
uploadDir, uploadDir,
maxUploadSize: parseMaxUploadSize(process.env.MAX_UPLOAD_SIZE ?? String(20 * 1024 * 1024)), maxUploadSize: parseMaxUploadSize(process.env.MAX_UPLOAD_SIZE ?? String(20 * 1024 * 1024)),
schedulerIntervalMs: Number.parseInt(process.env.SCHEDULER_INTERVAL_MS ?? '20000', 10), schedulerIntervalMs: Number.parseInt(process.env.SCHEDULER_INTERVAL_MS ?? '20000', 10),
+1 -1
View File
@@ -1,7 +1,7 @@
/** /**
* Ошибочный статус HTTP-ответа (подмножество используемых кодов). * Ошибочный статус HTTP-ответа (подмножество используемых кодов).
*/ */
export type ApiErrorCode = 400 | 401 | 403 | 404 | 409 | 500; export type ApiErrorCode = 400 | 401 | 403 | 404 | 409 | 413 | 500;
/** /**
* Ожидаемая (предусмотренная) ошибка приложения. * Ожидаемая (предусмотренная) ошибка приложения.