diff --git a/client/eslint.config.js b/client/eslint.config.js index 017e21c..ed889fb 100644 --- a/client/eslint.config.js +++ b/client/eslint.config.js @@ -95,6 +95,8 @@ export default defineConfig( 'react/no-unstable-nested-components': ['error', { allowAsProps: false }], /* В TS prop-types не нужны */ 'react/prop-types': 'off', + /* React 18 с jsx: react-jsx не требует React в scope */ + 'react/react-in-jsx-scope': 'off', }, }, diff --git a/client/src/App.tsx b/client/src/App.tsx new file mode 100644 index 0000000..6866ce8 --- /dev/null +++ b/client/src/App.tsx @@ -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 ( + + + + } /> + } /> + }> + } /> + + } /> + + + + ); +} diff --git a/client/src/api/client.ts b/client/src/api/client.ts new file mode 100644 index 0000000..02f2736 --- /dev/null +++ b/client/src/api/client.ts @@ -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)[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): Record { + const headers: Record = { ...extra }; + if (authToken !== null) { + headers.Authorization = `Bearer ${authToken}`; + } + return headers; +} + +/** + * Обрабатывает ответ: при 401 очищает токен, при !ok бросает ApiClientError. + * + * @param res — Response из fetch + * @returns распарсенный JSON + */ +async function handleResponse(res: Response): Promise { + 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( + path: string, + options: RequestInit = {}, +): Promise { + const extraHeaders: Record = { '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(res); +} + +/** + * Выполняет multipart/form-data запрос (для загрузки файлов). + * + * @param path — путь относительно /api + * @param formData — FormData объект + * @returns распарсенный JSON + */ +export async function apiUpload(path: string, formData: FormData): Promise { + const headers = buildHeaders(); + const res = await fetch(`${API_BASE}/api${path}`, { + method: 'POST', + headers, + body: formData, + }); + return handleResponse(res); +} diff --git a/client/src/api/types.ts b/client/src/api/types.ts new file mode 100644 index 0000000..a8a342f --- /dev/null +++ b/client/src/api/types.ts @@ -0,0 +1,9 @@ +/** + * Типы для API-ответов авторизации. + */ + +/** Ответ на регистрацию/логин. */ +export interface AuthResponse { + token: string; + user: { id: string; email: string }; +} diff --git a/client/src/auth/AuthContext.tsx b/client/src/auth/AuthContext.tsx new file mode 100644 index 0000000..ee1e64f --- /dev/null +++ b/client/src/auth/AuthContext.tsx @@ -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; + register: (email: string, password: string) => Promise; + logout: () => void; +} + +const AuthContext = createContext(undefined); + +/** + * Провайдер авторизации. Хранит token/userId в состоянии + localStorage. + */ +export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) { + const [token, setToken] = useState(() => localStorage.getItem('token')); + const [userId, setUserId] = useState(() => localStorage.getItem('userId')); + const [userEmail, setUserEmail] = useState(() => 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('/auth/login', { + method: 'POST', + body: JSON.stringify({ email, password }), + }); + handleAuth(res); + }, [handleAuth]); + + const register = useCallback(async (email: string, password: string) => { + const res = await apiFetch('/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(() => ({ + token, + userId, + userEmail, + isAuthenticated: token !== null, + login, + register, + logout, + }), [token, userId, userEmail, login, register, logout]); + + return {children}; +} + +/** + * Хук доступа к AuthContext. + * + * @throws если вне AuthProvider + */ +export function useAuth(): AuthContextValue { + const ctx = useContext(AuthContext); + if (!ctx) { + throw new Error('useAuth must be used within AuthProvider'); + } + return ctx; +} diff --git a/client/src/components/ProtectedRoute.tsx b/client/src/components/ProtectedRoute.tsx new file mode 100644 index 0000000..91329ca --- /dev/null +++ b/client/src/components/ProtectedRoute.tsx @@ -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 ; + } + + return ; +} diff --git a/client/src/main.tsx b/client/src/main.tsx new file mode 100644 index 0000000..b976ccc --- /dev/null +++ b/client/src/main.tsx @@ -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(); +} diff --git a/client/src/pages/HomePage.tsx b/client/src/pages/HomePage.tsx new file mode 100644 index 0000000..64eb7fb --- /dev/null +++ b/client/src/pages/HomePage.tsx @@ -0,0 +1,19 @@ +import { useAuth } from '../auth/AuthContext.js'; + +/** + * Главная страница (защитена ProtectedRoute). + * Показывает email пользователя и кнопку logout. + */ +export function HomePage() { + const { userEmail, logout } = useAuth(); + + return ( +
+

News Editor

+

Добро пожаловать, {userEmail}!

+ +
+ ); +} diff --git a/client/src/pages/LoginPage.tsx b/client/src/pages/LoginPage.tsx new file mode 100644 index 0000000..c2aeb8f --- /dev/null +++ b/client/src/pages/LoginPage.tsx @@ -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 ( +
+

Вход

+
+
+ + { setEmail(e.target.value); }} + required + autoComplete="email" + /> +
+
+ + { setPassword(e.target.value); }} + required + autoComplete="current-password" + /> +
+ {error ?

{error}

: null} + +
+

+ Нет аккаунта?{' '} + Зарегистрироваться +

+
+ ); +} diff --git a/client/src/pages/RegisterPage.tsx b/client/src/pages/RegisterPage.tsx new file mode 100644 index 0000000..35decd1 --- /dev/null +++ b/client/src/pages/RegisterPage.tsx @@ -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 ( +
+

Регистрация

+
+
+ + { setEmail(e.target.value); }} + required + autoComplete="email" + /> +
+
+ + { setPassword(e.target.value); }} + required + minLength={6} + autoComplete="new-password" + /> +
+
+ + { setConfirmPassword(e.target.value); }} + required + autoComplete="new-password" + /> +
+ {error ?

{error}

: null} + +
+

+ Уже есть аккаунт?{' '} + Войти +

+
+ ); +} diff --git a/client/src/styles/global.scss b/client/src/styles/global.scss new file mode 100644 index 0000000..5986d43 --- /dev/null +++ b/client/src/styles/global.scss @@ -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; + } +} diff --git a/client/src/vite-env.d.ts b/client/src/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/client/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/client/vite.config.js b/client/vite.config.js index f2af297..2e393a3 100644 --- a/client/vite.config.js +++ b/client/vite.config.js @@ -9,6 +9,12 @@ import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], server: { + host: true, port: 5173, + proxy: { + '/api': 'http://localhost:3000', + '/uploads': 'http://localhost:3000', + '/socket.io': { target: 'http://localhost:3000', ws: true }, + }, }, }); diff --git a/server/src/app.ts b/server/src/app.ts index 8e921f8..45fead6 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -27,8 +27,8 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp // Security headers app.use(helmet()); - // CORS — whitelist из CLIENT_ORIGIN - app.use(cors({ origin: env.clientOrigin })); + // CORS — whitelist из CLIENT_ORIGIN (поддерживается несколько через запятую) + app.use(cors({ origin: env.clientOrigins })); // Парсинг тела запроса app.use(json()); diff --git a/server/src/config/env.ts b/server/src/config/env.ts index 93fd2de..8806b98 100644 --- a/server/src/config/env.ts +++ b/server/src/config/env.ts @@ -36,6 +36,7 @@ export interface Env { readonly jwtSecret: string; readonly jwtExpiresIn: string; readonly clientOrigin: string; + readonly clientOrigins: string[]; readonly uploadDir: string; readonly maxUploadSize: number; readonly schedulerIntervalMs: number; @@ -105,6 +106,7 @@ export function loadEnv(): Env { jwtSecret: required('JWT_SECRET'), jwtExpiresIn: process.env.JWT_EXPIRES_IN ?? '7d', clientOrigin: process.env.CLIENT_ORIGIN ?? 'http://localhost:5173', + clientOrigins: (process.env.CLIENT_ORIGIN ?? 'http://localhost:5173').split(',').map((s) => s.trim()), uploadDir, maxUploadSize: parseMaxUploadSize(process.env.MAX_UPLOAD_SIZE ?? String(20 * 1024 * 1024)), schedulerIntervalMs: Number.parseInt(process.env.SCHEDULER_INTERVAL_MS ?? '20000', 10), diff --git a/server/src/utils/ApiError.ts b/server/src/utils/ApiError.ts index 199d500..48c237d 100644 --- a/server/src/utils/ApiError.ts +++ b/server/src/utils/ApiError.ts @@ -1,7 +1,7 @@ /** * Ошибочный статус HTTP-ответа (подмножество используемых кодов). */ -export type ApiErrorCode = 400 | 401 | 403 | 404 | 409 | 500; +export type ApiErrorCode = 400 | 401 | 403 | 404 | 409 | 413 | 500; /** * Ожидаемая (предусмотренная) ошибка приложения.