Ревью кода: исправление найденных проблем
This commit is contained in:
+6
-1
@@ -1 +1,6 @@
|
|||||||
VITE_API_URL=http://localhost:3000
|
# Базовый URL API для fetch.
|
||||||
|
# В dev — через Vite proxy (см. vite.config.ts): оставьте пустым или укажите http://localhost:3000.
|
||||||
|
# В production через reverse proxy — оставьте ПУСТЫМ (запросы пойдут на текущий origin,
|
||||||
|
# и nginx/HAProxy пробросит /api на backend). Указание http://localhost:3000 в production
|
||||||
|
# приведёт к двойному префиксу (браузер будет ходить на localhost:3000, а не на origin).
|
||||||
|
VITE_API_URL=
|
||||||
|
|||||||
+11
-3
@@ -329,19 +329,27 @@ export default defineConfig(
|
|||||||
'no-alert': 'off',
|
'no-alert': 'off',
|
||||||
// e.target.value = '' — сброс file input (стандартный паттерн)
|
// e.target.value = '' — сброс file input (стандартный паттерн)
|
||||||
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['e'] }],
|
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['e'] }],
|
||||||
// Навигация после await (window.location.href → useNavigate)
|
|
||||||
'require-atomic-updates': 'off',
|
|
||||||
// async IIFE в useEffect для загрузки новости
|
// async IIFE в useEffect для загрузки новости
|
||||||
'@typescript-eslint/no-floating-promises': 'off',
|
'@typescript-eslint/no-floating-promises': 'off',
|
||||||
// newsId гарантированно string (проверено isNew)
|
// newsId гарантированно string (проверено isNew)
|
||||||
'@typescript-eslint/restrict-template-expressions': 'off',
|
'@typescript-eslint/restrict-template-expressions': 'off',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'client/auth-context',
|
||||||
|
files: ['src/auth/AuthContext.tsx'],
|
||||||
|
rules: {
|
||||||
|
// onAuthExpired: navigate('/login') возвращает void,
|
||||||
|
// но линтер требует обработки (no-floating-promises)
|
||||||
|
'@typescript-eslint/no-floating-promises': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'client/auth-pages',
|
name: 'client/auth-pages',
|
||||||
files: ['src/pages/LoginPage.tsx', 'src/pages/RegisterPage.tsx'],
|
files: ['src/pages/LoginPage.tsx', 'src/pages/RegisterPage.tsx'],
|
||||||
rules: {
|
rules: {
|
||||||
// .then()/.catch() в цепочке — не floating promise
|
// .then/.catch/.finally цепочка в handleSubmit: rejection обработан,
|
||||||
|
// но no-floating-promises не распознаёт pattern (см. комментарий в файле)
|
||||||
'@typescript-eslint/no-floating-promises': 'off',
|
'@typescript-eslint/no-floating-promises': 'off',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* API-клиент: fetch-обёртка с автоматическим Authorization header
|
* API-клиент: fetch-обёртка с автоматическим Authorization header
|
||||||
* и обработкой 401 (logout при истёкшем токене).
|
* и обработкой 401 (событие 'auth:expired' для AuthContext).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -68,6 +68,17 @@ function buildHeaders(extra?: Record<string, string>): Record<string, string> {
|
|||||||
return headers;
|
return headers;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Обработка истёкшего токена (401): очищаем токен и уведомляем AuthContext.
|
||||||
|
*
|
||||||
|
* AuthContext подписывается на событие 'auth:expired' и сам делает logout
|
||||||
|
* + navigate — здесь мы не трогам роутер (client.ts не знает про React).
|
||||||
|
*/
|
||||||
|
function handleUnauthorized(): void {
|
||||||
|
setAuthToken(null);
|
||||||
|
window.dispatchEvent(new Event('auth:expired'));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Обрабатывает ответ: при 401 очищает токен, при !ok бросает ApiClientError.
|
* Обрабатывает ответ: при 401 очищает токен, при !ok бросает ApiClientError.
|
||||||
*
|
*
|
||||||
@@ -76,8 +87,7 @@ function buildHeaders(extra?: Record<string, string>): Record<string, string> {
|
|||||||
*/
|
*/
|
||||||
async function handleResponse<T>(res: Response): Promise<T> {
|
async function handleResponse<T>(res: Response): Promise<T> {
|
||||||
if (res.status === 401 && authToken !== null) {
|
if (res.status === 401 && authToken !== null) {
|
||||||
setAuthToken(null);
|
handleUnauthorized();
|
||||||
window.location.href = '/login';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = (await res.json().catch(() => ({}))) as unknown as ApiErrorBody & T;
|
const data = (await res.json().catch(() => ({}))) as unknown as ApiErrorBody & T;
|
||||||
|
|||||||
@@ -24,9 +24,9 @@ export interface NewsItem {
|
|||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ответ на upload. */
|
/** Ответ на upload (сервер возвращает { file: { name, url } }). */
|
||||||
export interface UploadResponse {
|
export interface UploadResponse {
|
||||||
file: { url: string; filename: string; size: number };
|
file: { name: string; url: string };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Тип уведомления. */
|
/** Тип уведомления. */
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';
|
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
import { apiFetch, setAuthToken } from '../api/client.js';
|
import { apiFetch, setAuthToken } from '../api/client.js';
|
||||||
|
|
||||||
@@ -27,12 +28,19 @@ interface AuthContextValue {
|
|||||||
logout: () => void;
|
logout: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Имя события об истёкшем токене (выпускается api/client.ts при 401
|
||||||
|
* и при connect_error Socket.IO с UNAUTHORIZED).
|
||||||
|
*/
|
||||||
|
export const AUTH_EXPIRED_EVENT = 'auth:expired';
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Провайдер авторизации. Хранит token/userId в состоянии + localStorage.
|
* Провайдер авторизации. Хранит token/userId в состоянии + localStorage.
|
||||||
*/
|
*/
|
||||||
export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
|
export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
|
||||||
|
const navigate = useNavigate();
|
||||||
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
|
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
|
||||||
const [userId, setUserId] = useState<string | null>(() => localStorage.getItem('userId'));
|
const [userId, setUserId] = useState<string | null>(() => localStorage.getItem('userId'));
|
||||||
const [userEmail, setUserEmail] = useState<string | null>(() => localStorage.getItem('userEmail'));
|
const [userEmail, setUserEmail] = useState<string | null>(() => localStorage.getItem('userEmail'));
|
||||||
@@ -62,15 +70,33 @@ export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
|
|||||||
handleAuth(res);
|
handleAuth(res);
|
||||||
}, [handleAuth]);
|
}, [handleAuth]);
|
||||||
|
|
||||||
const logout = useCallback(() => {
|
/**
|
||||||
|
* Logout: очистка токена/данных пользователя.
|
||||||
|
* @returns void — вызывается fire-and-forget (navigate после logout)
|
||||||
|
*/
|
||||||
|
const logout = useCallback((): void => {
|
||||||
setAuthToken(null);
|
setAuthToken(null);
|
||||||
setToken(null);
|
setToken(null);
|
||||||
setUserId(null);
|
setUserId(null);
|
||||||
setUserEmail(null);
|
setUserEmail(null);
|
||||||
localStorage.removeItem('userId');
|
localStorage.removeItem('userId');
|
||||||
localStorage.removeItem('userEmail');
|
localStorage.removeItem('userEmail');
|
||||||
|
// navigate('/login') вызывается вызывающей стороной (onAuthExpired)
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// При 401 (истёкший токен) — logout + редирект на /login.
|
||||||
|
// Событие выпускается api/client.ts и useSocket.ts.
|
||||||
|
useEffect(() => {
|
||||||
|
const onAuthExpired = (): void => {
|
||||||
|
logout();
|
||||||
|
navigate('/login');
|
||||||
|
};
|
||||||
|
window.addEventListener(AUTH_EXPIRED_EVENT, onAuthExpired);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener(AUTH_EXPIRED_EVENT, onAuthExpired);
|
||||||
|
};
|
||||||
|
}, [logout, navigate]);
|
||||||
|
|
||||||
const value = useMemo<AuthContextValue>(() => ({
|
const value = useMemo<AuthContextValue>(() => ({
|
||||||
token,
|
token,
|
||||||
userId,
|
userId,
|
||||||
|
|||||||
@@ -1,27 +1,13 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
import { useNotifications } from '../hooks/useNotifications.js';
|
import { useNotifications } from '../hooks/useNotifications.js';
|
||||||
|
import { formatDateTime } from '../utils/formatDate.js';
|
||||||
|
|
||||||
import styles from './NotificationBell.module.scss';
|
import styles from './NotificationBell.module.scss';
|
||||||
|
|
||||||
import type { NotificationItem } from '../api/types.js';
|
import type { NotificationItem } from '../api/types.js';
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Форматирует дату в коротком формате.
|
|
||||||
*
|
|
||||||
* @param iso — ISO-дата
|
|
||||||
* @returns строка вида "16.08 12:30"
|
|
||||||
*/
|
|
||||||
function formatDateTime(iso: string): string {
|
|
||||||
const d = new Date(iso);
|
|
||||||
const day = String(d.getDate()).padStart(2, '0');
|
|
||||||
const month = String(d.getMonth() + 1).padStart(2, '0');
|
|
||||||
const hours = String(d.getHours()).padStart(2, '0');
|
|
||||||
const minutes = String(d.getMinutes()).padStart(2, '0');
|
|
||||||
return `${day}.${month} ${hours}:${minutes}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Одиночное уведомление в списке.
|
* Одиночное уведомление в списке.
|
||||||
*/
|
*/
|
||||||
@@ -60,11 +46,11 @@ export function NotificationBell({ token }: { readonly token: string | null }) {
|
|||||||
} = useNotifications(token);
|
} = useNotifications(token);
|
||||||
|
|
||||||
const handleMarkAsRead = (id: string): void => {
|
const handleMarkAsRead = (id: string): void => {
|
||||||
markAsRead(id).catch(() => { /* ignore */ });
|
void markAsRead(id).catch(() => { /* ignore */ });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMarkAll = (): void => {
|
const handleMarkAll = (): void => {
|
||||||
markAllAsRead().catch(() => { /* ignore */ });
|
void markAllAsRead().catch(() => { /* ignore */ });
|
||||||
};
|
};
|
||||||
|
|
||||||
if (token === null) {
|
if (token === null) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
import { apiFetch, apiUpload } from '../api/client.js';
|
import { apiFetch, apiUpload } from '../api/client.js';
|
||||||
|
|
||||||
@@ -50,6 +51,29 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [scheduleDate, setScheduleDate] = useState('');
|
const [scheduleDate, setScheduleDate] = useState('');
|
||||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Общий хелпер для CRUD-действий: saving-флаг, сброс/установка error, catch.
|
||||||
|
* Навигация (если нужна) выполняется внутри action.
|
||||||
|
*
|
||||||
|
* @param action — асинхронная операция
|
||||||
|
* @param fallbackMessage — сообщение об ошибке по умолчанию
|
||||||
|
*/
|
||||||
|
const runAction = useCallback(
|
||||||
|
(action: () => Promise<void>, fallbackMessage: string): void => {
|
||||||
|
setSaving(true);
|
||||||
|
setError('');
|
||||||
|
void action()
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
setError(err instanceof Error ? err.message : fallbackMessage);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
setSaving(false);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
/** Вставляет markdown-фрагмент в textarea на позиции курсора. */
|
/** Вставляет markdown-фрагмент в textarea на позиции курсора. */
|
||||||
const insertMarkdown = useCallback((before: string, after = ''): void => {
|
const insertMarkdown = useCallback((before: string, after = ''): void => {
|
||||||
@@ -69,54 +93,41 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
});
|
});
|
||||||
}, [content, setContent]);
|
}, [content, setContent]);
|
||||||
|
|
||||||
/** Сохраняет черновик. */
|
/** Сохраняет черновик. Новая новость → переход на /news. */
|
||||||
const handleSave = useCallback(async (): Promise<void> => {
|
const onSave = useCallback((): void => {
|
||||||
setSaving(true);
|
runAction(async () => {
|
||||||
setError('');
|
|
||||||
try {
|
|
||||||
if (isNew) {
|
if (isNew) {
|
||||||
await apiFetch('/news', {
|
await apiFetch('/news', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ title, content }),
|
body: JSON.stringify({ title, content }),
|
||||||
});
|
});
|
||||||
|
navigate('/news');
|
||||||
window.location.href = '/news';
|
return;
|
||||||
} else {
|
}
|
||||||
await apiFetch(`/news/${newsId}`, {
|
await apiFetch(`/news/${newsId}`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
body: JSON.stringify({ title, content }),
|
body: JSON.stringify({ title, content }),
|
||||||
});
|
});
|
||||||
setError('Сохранено ✓');
|
setError('Сохранено ✓');
|
||||||
setTimeout(() => { setError(''); }, 2000);
|
setTimeout(() => { setError(''); }, 2000);
|
||||||
}
|
}, 'Ошибка сохранения');
|
||||||
} catch (err) {
|
}, [runAction, isNew, newsId, title, content, navigate]);
|
||||||
setError(err instanceof Error ? err.message : 'Ошибка сохранения');
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
}, [isNew, newsId, title, content]);
|
|
||||||
|
|
||||||
/** Публикует немедленно. */
|
/** Публикует немедленно. */
|
||||||
const handlePublish = useCallback(async (): Promise<void> => {
|
const onPublish = useCallback((): void => {
|
||||||
|
runAction(async () => {
|
||||||
if (newsId === undefined) {
|
if (newsId === undefined) {
|
||||||
setError('Сначала сохраните черновик');
|
setError('Сначала сохраните черновик');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSaving(true);
|
|
||||||
setError('');
|
|
||||||
try {
|
|
||||||
await apiFetch(`/news/${newsId}/publish`, { method: 'POST' });
|
await apiFetch(`/news/${newsId}/publish`, { method: 'POST' });
|
||||||
|
navigate('/news');
|
||||||
window.location.href = '/news';
|
}, 'Ошибка публикации');
|
||||||
} catch (err) {
|
}, [runAction, newsId, navigate]);
|
||||||
setError(err instanceof Error ? err.message : 'Ошибка публикации');
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
}, [newsId]);
|
|
||||||
|
|
||||||
/** Планирует публикацию. */
|
/** Планирует публикацию. */
|
||||||
const handleSchedule = useCallback(async (): Promise<void> => {
|
const onSchedule = useCallback((): void => {
|
||||||
|
runAction(async () => {
|
||||||
if (newsId === undefined) {
|
if (newsId === undefined) {
|
||||||
setError('Сначала сохраните черновик');
|
setError('Сначала сохраните черновик');
|
||||||
return;
|
return;
|
||||||
@@ -125,41 +136,29 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
setError('Выберите дату публикации');
|
setError('Выберите дату публикации');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSaving(true);
|
// datetime-local даёт local time — конвертируем в ISO (UTC) для сервера
|
||||||
setError('');
|
const iso = new Date(scheduleDate).toISOString();
|
||||||
try {
|
|
||||||
await apiFetch(`/news/${newsId}/schedule`, {
|
await apiFetch(`/news/${newsId}/schedule`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ scheduledAt: scheduleDate }),
|
body: JSON.stringify({ scheduledAt: iso }),
|
||||||
});
|
});
|
||||||
|
navigate('/news');
|
||||||
window.location.href = '/news';
|
}, 'Ошибка планирования');
|
||||||
} catch (err) {
|
}, [runAction, newsId, scheduleDate, navigate]);
|
||||||
setError(err instanceof Error ? err.message : 'Ошибка планирования');
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
}, [newsId, scheduleDate]);
|
|
||||||
|
|
||||||
/** Удаляет новость. */
|
/** Удаляет новость. */
|
||||||
const handleDelete = useCallback(async (): Promise<void> => {
|
const onDelete = useCallback((): void => {
|
||||||
|
runAction(async () => {
|
||||||
if (newsId === undefined) {
|
if (newsId === undefined) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!window.confirm('Удалить новость?')) {
|
if (!window.confirm('Удалить новость?')) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSaving(true);
|
|
||||||
setError('');
|
|
||||||
try {
|
|
||||||
await apiFetch(`/news/${newsId}`, { method: 'DELETE' });
|
await apiFetch(`/news/${newsId}`, { method: 'DELETE' });
|
||||||
window.location.href = '/news';
|
navigate('/news');
|
||||||
} catch (err) {
|
}, 'Ошибка удаления');
|
||||||
setError(err instanceof Error ? err.message : 'Ошибка удаления');
|
}, [runAction, newsId, navigate]);
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
}, [newsId]);
|
|
||||||
|
|
||||||
/** Загружает файл и вставляет markdown-ссылку. */
|
/** Загружает файл и вставляет markdown-ссылку. */
|
||||||
const handleFileUpload = useCallback(async (file: File, isImage: boolean): Promise<void> => {
|
const handleFileUpload = useCallback(async (file: File, isImage: boolean): Promise<void> => {
|
||||||
@@ -176,23 +175,6 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
}
|
}
|
||||||
}, [insertMarkdown]);
|
}, [insertMarkdown]);
|
||||||
|
|
||||||
// Обёртки для onClick: .catch() чтобы не триггерить no-floating-promises
|
|
||||||
const onSave = useCallback((): void => {
|
|
||||||
handleSave().catch((e: unknown) => { console.error('Save failed', e); });
|
|
||||||
}, [handleSave]);
|
|
||||||
|
|
||||||
const onPublish = useCallback((): void => {
|
|
||||||
handlePublish().catch((e: unknown) => { console.error('Publish failed', e); });
|
|
||||||
}, [handlePublish]);
|
|
||||||
|
|
||||||
const onDelete = useCallback((): void => {
|
|
||||||
handleDelete().catch((e: unknown) => { console.error('Delete failed', e); });
|
|
||||||
}, [handleDelete]);
|
|
||||||
|
|
||||||
const onSchedule = useCallback((): void => {
|
|
||||||
handleSchedule().catch((e: unknown) => { console.error('Schedule failed', e); });
|
|
||||||
}, [handleSchedule]);
|
|
||||||
|
|
||||||
/** Обработчик toolbar-кнопок. */
|
/** Обработчик toolbar-кнопок. */
|
||||||
const handleToolbarAction = useCallback((action: string): void => {
|
const handleToolbarAction = useCallback((action: string): void => {
|
||||||
if (action === 'bold') { insertMarkdown('**', '**'); }
|
if (action === 'bold') { insertMarkdown('**', '**'); }
|
||||||
@@ -207,7 +189,7 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file !== undefined) {
|
if (file !== undefined) {
|
||||||
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
|
void handleFileUpload(file, true);
|
||||||
}
|
}
|
||||||
e.target.value = '';
|
e.target.value = '';
|
||||||
}, [handleFileUpload]);
|
}, [handleFileUpload]);
|
||||||
@@ -216,7 +198,7 @@ export function useNewsEditor(newsId: string | undefined) {
|
|||||||
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file !== undefined) {
|
if (file !== undefined) {
|
||||||
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
|
void handleFileUpload(file, false);
|
||||||
}
|
}
|
||||||
e.target.value = '';
|
e.target.value = '';
|
||||||
}, [handleFileUpload]);
|
}, [handleFileUpload]);
|
||||||
|
|||||||
@@ -29,8 +29,9 @@ export function useNotifications(token: string | null) {
|
|||||||
]);
|
]);
|
||||||
setNotifications(listRes.notifications);
|
setNotifications(listRes.notifications);
|
||||||
setUnreadCount(countRes.count);
|
setUnreadCount(countRes.count);
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Ошибка загрузки — игнорируем (user может быть offline)
|
// Ошибка загрузки — логируем, user может быть offline
|
||||||
|
console.error('Не удалось загрузить уведомления:', err);
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -40,8 +41,8 @@ export function useNotifications(token: string | null) {
|
|||||||
await apiFetch(`/notifications/${id}/read`, { method: 'PATCH' });
|
await apiFetch(`/notifications/${id}/read`, { method: 'PATCH' });
|
||||||
setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, isRead: true } : n));
|
setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, isRead: true } : n));
|
||||||
setUnreadCount((prev) => Math.max(0, prev - 1));
|
setUnreadCount((prev) => Math.max(0, prev - 1));
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Игнорируем ошибку
|
console.error('Не удалось отметить уведомление прочитанным:', err);
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -51,8 +52,8 @@ export function useNotifications(token: string | null) {
|
|||||||
await apiFetch('/notifications/read-all', { method: 'POST' });
|
await apiFetch('/notifications/read-all', { method: 'POST' });
|
||||||
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
|
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
|
||||||
setUnreadCount(0);
|
setUnreadCount(0);
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Игнорируем ошибку
|
console.error('Не удалось отметить все уведомления прочитанными:', err);
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { io, type Socket } from 'socket.io-client';
|
import { io, type Socket } from 'socket.io-client';
|
||||||
|
|
||||||
|
import { AUTH_EXPIRED_EVENT } from '../auth/AuthContext.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Подключается к Socket.IO серверу с JWT-аутентификацией.
|
* Подключается к Socket.IO серверу с JWT-аутентификацией.
|
||||||
*
|
*
|
||||||
|
* При connect_error с UNAUTHORIZED (истёкший/невалидный JWT) — выпускает
|
||||||
|
* событие 'auth:expired': AuthContext делает logout + navigate.
|
||||||
|
* Это прерывает бесконечный reconnect loop с мёртвым токеном.
|
||||||
|
*
|
||||||
* @param token — JWT токен пользователя
|
* @param token — JWT токен пользователя
|
||||||
* @param url — URL Socket.IO сервера (по умолчанию — текущий origin)
|
* @param url — URL Socket.IO сервера (по умолчанию — текущий origin)
|
||||||
* @returns socket или null (если не подключено)
|
* @returns socket или null (если не подключено)
|
||||||
@@ -23,9 +29,24 @@ export function useSocket(token: string | null, url?: string): Socket | null {
|
|||||||
transports: ['websocket', 'polling'],
|
transports: ['websocket', 'polling'],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// UNAUTHORIZED на handshake — не ререконнектимся бесконечно:
|
||||||
|
// логируем, отключаем и уведомляем AuthContext.
|
||||||
|
const onConnectError = (err: Error): void => {
|
||||||
|
const isUnauthorized =
|
||||||
|
err.message.includes('UNAUTHORIZED') || err.message.includes('недействительный токен');
|
||||||
|
if (!isUnauthorized) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.warn('Socket.IO: токен недействителен, разрываем соединение', err.message);
|
||||||
|
newSocket.disconnect();
|
||||||
|
window.dispatchEvent(new Event(AUTH_EXPIRED_EVENT));
|
||||||
|
};
|
||||||
|
newSocket.on('connect_error', onConnectError);
|
||||||
|
|
||||||
setSocket(newSocket);
|
setSocket(newSocket);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
|
newSocket.off('connect_error', onConnectError);
|
||||||
newSocket.disconnect();
|
newSocket.disconnect();
|
||||||
setSocket(null);
|
setSocket(null);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
|
|||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
|
|
||||||
import { apiFetch } from '../api/client.js';
|
import { apiFetch } from '../api/client.js';
|
||||||
|
import { formatDateTime } from '../utils/formatDate.js';
|
||||||
|
|
||||||
import styles from './NewsListPage.module.scss';
|
import styles from './NewsListPage.module.scss';
|
||||||
|
|
||||||
@@ -17,16 +18,20 @@ export function NewsListPage() {
|
|||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void (async () => {
|
/** Загружает список новостей. */
|
||||||
|
async function loadNews(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const data = await apiFetch<{ news: NewsItem[] }>('/news');
|
const data = await apiFetch<{ news: NewsItem[] }>('/news');
|
||||||
setNews(data.news);
|
setNews(data.news);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Ошибка загрузки');
|
setError(err instanceof Error ? err.message : 'Ошибка загрузки');
|
||||||
|
// При 401 api-клиент уже очистил токен и выпустил auth:expired —
|
||||||
|
// AuthContext сделает logout + navigate('/login')
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
})();
|
}
|
||||||
|
loadNews().catch(() => { /* ошибки обработаны внутри loadNews */ });
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
@@ -63,7 +68,7 @@ export function NewsListPage() {
|
|||||||
<div className={styles.cardMeta}>
|
<div className={styles.cardMeta}>
|
||||||
<span className={`${styles.badge} ${styles[item.status]}`}>{item.status}</span>
|
<span className={`${styles.badge} ${styles[item.status]}`}>{item.status}</span>
|
||||||
<span className={styles.cardDate}>
|
<span className={styles.cardDate}>
|
||||||
{new Date(item.updatedAt).toLocaleString('ru-RU')}
|
{formatDateTime(item.updatedAt)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
/**
|
||||||
|
* Единый формат даты для всего клиентского приложения.
|
||||||
|
*
|
||||||
|
* @param iso — ISO-дата
|
||||||
|
* @returns строка вида "16.08 12:30" (короткий формат без года)
|
||||||
|
*/
|
||||||
|
export function formatDateTime(iso: string): string {
|
||||||
|
const d = new Date(iso);
|
||||||
|
const day = String(d.getDate()).padStart(2, '0');
|
||||||
|
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||||
|
const hours = String(d.getHours()).padStart(2, '0');
|
||||||
|
const minutes = String(d.getMinutes()).padStart(2, '0');
|
||||||
|
return `${day}.${month} ${hours}:${minutes}`;
|
||||||
|
}
|
||||||
+11
-1
@@ -300,9 +300,19 @@ export default defineConfig(
|
|||||||
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'server/jwt',
|
||||||
|
files: ['src/utils/jwt.ts'],
|
||||||
|
rules: {
|
||||||
|
// env.jwtExpiresIn — string, а SignOptions.expiresIn ожидает StringValue из пакета ms;
|
||||||
|
// double-assertion — стандартная практика для env-значений
|
||||||
|
'@typescript-eslint/consistent-type-assertions': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-type-assertion': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'server/import-default-exports',
|
name: 'server/import-default-exports',
|
||||||
files: ['src/app.ts', 'src/utils/jwt.ts', 'src/middleware/upload.middleware.ts'],
|
files: ['src/app.ts', 'src/middleware/upload.middleware.ts', 'src/utils/jwt.ts'],
|
||||||
rules: {
|
rules: {
|
||||||
// express.static, jwt.sign/verify, multer.diskStorage — default export API
|
// express.static, jwt.sign/verify, multer.diskStorage — default export API
|
||||||
'import-x/no-named-as-default-member': 'off',
|
'import-x/no-named-as-default-member': 'off',
|
||||||
|
|||||||
@@ -33,13 +33,6 @@ export function createApp(options?: CreateAppOptions): express.Express {
|
|||||||
const app = express();
|
const app = express();
|
||||||
const { io, extraMiddleware } = options ?? {};
|
const { io, extraMiddleware } = options ?? {};
|
||||||
|
|
||||||
// /socket.io — Socket.IO (engine.io) обрабатывает на уровне HTTP server.
|
|
||||||
// Express НЕ отвечает на эти запросы (не вызывает res.send/next).
|
|
||||||
// Socket.IO handler (второй listener) получает те же req/res и отвечает.
|
|
||||||
app.use('/socket.io', () => {
|
|
||||||
// Intentionally empty — не отвечаем, Socket.IO обработает
|
|
||||||
});
|
|
||||||
|
|
||||||
// Security headers
|
// Security headers
|
||||||
app.use(helmet());
|
app.use(helmet());
|
||||||
|
|
||||||
|
|||||||
@@ -87,6 +87,51 @@ function parseMaxUploadSize(raw: string): number {
|
|||||||
return size;
|
return size;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Валидирует и возвращает интервал опроса scheduler в мс.
|
||||||
|
*
|
||||||
|
* @param raw — строковое значение из окружения
|
||||||
|
* @returns валидированный интервал
|
||||||
|
* @throws {Error} если значение некорректно (NaN или меньше 1000 мс)
|
||||||
|
*/
|
||||||
|
function parseSchedulerInterval(raw: string): number {
|
||||||
|
const interval = Number.parseInt(raw, 10);
|
||||||
|
if (Number.isNaN(interval) || interval < 1000) {
|
||||||
|
throw new Error(`Некорректное значение SCHEDULER_INTERVAL_MS: ${raw} (нужно целое >= 1000)`);
|
||||||
|
}
|
||||||
|
return interval;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Валидирует каталог для загружаемых файлов.
|
||||||
|
*
|
||||||
|
* Относительные пути разрешаются от корня server/. Каталог не может
|
||||||
|
* быть корневым FS или чувствительной директорией (home, .env и т.п.) —
|
||||||
|
* express.static отдаёт всё из этого каталога.
|
||||||
|
*
|
||||||
|
* @param raw — значение UPLOAD_DIR из окружения
|
||||||
|
* @returns абсолютный путь к каталогу
|
||||||
|
* @throws {Error} если путь некорректен
|
||||||
|
*/
|
||||||
|
function parseUploadDir(raw: string): string {
|
||||||
|
const resolved = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(SERVER_ROOT, raw);
|
||||||
|
|
||||||
|
// Корень ФС — недопустим (static отдаст всю файловую систему)
|
||||||
|
if (resolved === path.parse(resolved).root) {
|
||||||
|
throw new Error('UPLOAD_DIR не может быть корневым каталогом файловой системы');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Чувствительные директории — недопустимы
|
||||||
|
const sensitive = ['..', '.env', '.git', 'src', 'dist', 'tests', 'node_modules', '.npm'];
|
||||||
|
const parts = resolved.split(path.sep).filter((p) => p.length > 0);
|
||||||
|
const last = parts[parts.length - 1];
|
||||||
|
if (sensitive.includes(last)) {
|
||||||
|
throw new Error(`UPLOAD_DIR не может быть чувствительной директорией: ${raw}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Загружает все переменные окружения с валидацией.
|
* Загружает все переменные окружения с валидацией.
|
||||||
*
|
*
|
||||||
@@ -94,10 +139,7 @@ function parseMaxUploadSize(raw: string): number {
|
|||||||
* @throws {Error} если отсутствуют обязательные переменные или значения некорректны
|
* @throws {Error} если отсутствуют обязательные переменные или значения некорректны
|
||||||
*/
|
*/
|
||||||
export function loadEnv(): Env {
|
export function loadEnv(): Env {
|
||||||
const uploadDirRaw = process.env.UPLOAD_DIR ?? 'uploads';
|
const clientOrigin = process.env.CLIENT_ORIGIN ?? 'http://localhost:5173';
|
||||||
const uploadDir = path.isAbsolute(uploadDirRaw)
|
|
||||||
? uploadDirRaw
|
|
||||||
: path.join(SERVER_ROOT, uploadDirRaw);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
nodeEnv: process.env.NODE_ENV ?? 'development',
|
nodeEnv: process.env.NODE_ENV ?? 'development',
|
||||||
@@ -105,11 +147,11 @@ export function loadEnv(): Env {
|
|||||||
mongoUri: required('MONGODB_URI'),
|
mongoUri: required('MONGODB_URI'),
|
||||||
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,
|
||||||
clientOrigins: (process.env.CLIENT_ORIGIN ?? 'http://localhost:5173').split(',').map((s) => s.trim()),
|
clientOrigins: clientOrigin.split(',').map((s) => s.trim()),
|
||||||
uploadDir,
|
uploadDir: parseUploadDir(process.env.UPLOAD_DIR ?? 'uploads'),
|
||||||
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: parseSchedulerInterval(process.env.SCHEDULER_INTERVAL_MS ?? '20000'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,24 +3,16 @@ import { verifyUserToken } from '../utils/jwt.js';
|
|||||||
|
|
||||||
import type { NextFunction, Request, Response } from 'express';
|
import type { NextFunction, Request, Response } from 'express';
|
||||||
|
|
||||||
/**
|
|
||||||
* Расширенный запрос с данными авторизованного пользователя.
|
|
||||||
*
|
|
||||||
* Устанавливается auth middleware после успешной верификации Bearer-токена.
|
|
||||||
*/
|
|
||||||
export interface AuthenticatedRequest extends Request {
|
|
||||||
user?: { id: string };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Middleware авторизации.
|
* Middleware авторизации.
|
||||||
*
|
*
|
||||||
* Читает заголовок `Authorization: Bearer <token>`, верифицирует JWT
|
* Читает заголовок `Authorization: Bearer <token>`, верифицирует JWT
|
||||||
* и устанавливает `req.user.id` для последующих обработчиков.
|
* и устанавливает `req.user.id` для последующих обработчиков
|
||||||
|
* (req.user расширен declaration merging в types/express.d.ts).
|
||||||
* При отсутствии или невалидном токене — бросает ApiError 401.
|
* При отсутствии или невалидном токене — бросает ApiError 401.
|
||||||
*
|
*
|
||||||
* @param req — запрос Express
|
* @param req — запрос Express
|
||||||
* @param res — ответ Express
|
* @param _res — ответ Express
|
||||||
* @param next — функция продолжения цепочки middleware
|
* @param next — функция продолжения цепочки middleware
|
||||||
*/
|
*/
|
||||||
export function requireAuth(req: Request, _res: Response, next: NextFunction): void {
|
export function requireAuth(req: Request, _res: Response, next: NextFunction): void {
|
||||||
@@ -40,7 +32,7 @@ export function requireAuth(req: Request, _res: Response, next: NextFunction): v
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = verifyUserToken(token);
|
const payload = verifyUserToken(token);
|
||||||
(req as AuthenticatedRequest).user = { id: payload.id };
|
req.user = { id: payload.id };
|
||||||
next();
|
next();
|
||||||
} catch {
|
} catch {
|
||||||
next(new ApiError(401, 'UNAUTHORIZED', 'Невалидный или истёкший токен'));
|
next(new ApiError(401, 'UNAUTHORIZED', 'Невалидный или истёкший токен'));
|
||||||
|
|||||||
@@ -48,8 +48,6 @@ const newsSchema = new Schema<INews>(
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
timestamps: true,
|
timestamps: true,
|
||||||
toJSON: { virtuals: true },
|
|
||||||
toObject: { virtuals: true },
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ const notificationSchema = new Schema<INotification>(
|
|||||||
actor: {
|
actor: {
|
||||||
type: Schema.Types.ObjectId,
|
type: Schema.Types.ObjectId,
|
||||||
ref: 'User',
|
ref: 'User',
|
||||||
|
// Могут совпадать с user (однопользовательский сценарий) или
|
||||||
|
// быть null (системные уведомления). Mongoose кастит string → ObjectId.
|
||||||
default: null,
|
default: null,
|
||||||
},
|
},
|
||||||
type: {
|
type: {
|
||||||
|
|||||||
@@ -16,9 +16,13 @@ export type UserDocument = HydratedDocument<IUser>;
|
|||||||
/**
|
/**
|
||||||
* Схема пользователя.
|
* Схема пользователя.
|
||||||
*
|
*
|
||||||
* @property email — уникальный email (индекс)
|
* @property email — уникальный email (unique: true создаёт индекс,
|
||||||
|
* повторный index: true не нужен)
|
||||||
* @property passwordHash — хеш пароля (bcrypt, cost 12)
|
* @property passwordHash — хеш пароля (bcrypt, cost 12)
|
||||||
* @property createdAt / updatedAt — автоматические timestamps
|
* @property createdAt / updatedAt — автоматические timestamps
|
||||||
|
*
|
||||||
|
* Примечание: нормализация email (trim/lowercase) выполняется один раз
|
||||||
|
* в auth.routes.ts (extractCredentials) — schema не дублирует её.
|
||||||
*/
|
*/
|
||||||
const userSchema = new mongoose.Schema<IUser>(
|
const userSchema = new mongoose.Schema<IUser>(
|
||||||
{
|
{
|
||||||
@@ -26,8 +30,6 @@ const userSchema = new mongoose.Schema<IUser>(
|
|||||||
type: String,
|
type: String,
|
||||||
required: true,
|
required: true,
|
||||||
unique: true,
|
unique: true,
|
||||||
lowercase: true,
|
|
||||||
trim: true,
|
|
||||||
},
|
},
|
||||||
passwordHash: {
|
passwordHash: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -67,7 +69,3 @@ export async function hashPassword(password: string): Promise<string> {
|
|||||||
export async function comparePassword(password: string, hashValue: string): Promise<boolean> {
|
export async function comparePassword(password: string, hashValue: string): Promise<boolean> {
|
||||||
return compare(password, hashValue);
|
return compare(password, hashValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,12 +6,35 @@ import { ApiError } from '../utils/ApiError.js';
|
|||||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||||
import { signUserToken } from '../utils/jwt.js';
|
import { signUserToken } from '../utils/jwt.js';
|
||||||
|
|
||||||
import type { AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
|
||||||
import type { Request, Response } from 'express';
|
import type { Request, Response } from 'express';
|
||||||
|
|
||||||
|
/** Сообщение об ошибке авторизации. */
|
||||||
|
const AUTH_MSG = 'Требуется авторизация';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Проверяет email: не пуст, длина до 254, содержит @ и точку в домене.
|
||||||
|
*
|
||||||
|
* @param emailStr — нормализованный email
|
||||||
|
* @returns true, если формат приемлем
|
||||||
|
*/
|
||||||
|
function isValidEmail(emailStr: string): boolean {
|
||||||
|
if (emailStr.length === 0 || emailStr.length > 254) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const at = emailStr.indexOf('@');
|
||||||
|
if (at <= 0 || at === emailStr.length - 1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const domain = emailStr.slice(at + 1);
|
||||||
|
return domain.includes('.') && !domain.startsWith('.') && !domain.endsWith('.');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Извлекает email и password из тела запроса с подробной валидацией.
|
* Извлекает email и password из тела запроса с подробной валидацией.
|
||||||
*
|
*
|
||||||
|
* Нормализация email (trim + lowercase) выполняется один раз здесь —
|
||||||
|
* в схеме Mongoose не дублируется.
|
||||||
|
*
|
||||||
* @param rawBody — тело запроса (any из Express)
|
* @param rawBody — тело запроса (any из Express)
|
||||||
* @returns объект с валидированными email и password
|
* @returns объект с валидированными email и password
|
||||||
* @throws {ApiError} с конкретным сообщением о проблеме
|
* @throws {ApiError} с конкретным сообщением о проблеме
|
||||||
@@ -23,13 +46,13 @@ function extractCredentials(rawBody: unknown): { email: string; password: string
|
|||||||
const record = rawBody as Record<string, unknown>;
|
const record = rawBody as Record<string, unknown>;
|
||||||
const email = record.email;
|
const email = record.email;
|
||||||
const password = record.password;
|
const password = record.password;
|
||||||
const emailStr = typeof email === 'string' ? email.trim().toLowerCase() : '';
|
const emailStr = typeof email === 'string' ? email.trim() : '';
|
||||||
const passwordStr = typeof password === 'string' ? password : '';
|
const passwordStr = typeof password === 'string' ? password : '';
|
||||||
|
|
||||||
if (emailStr.length === 0) {
|
if (emailStr.length === 0) {
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Email не указан');
|
throw new ApiError(400, 'VALIDATION_ERROR', 'Email не указан');
|
||||||
}
|
}
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailStr)) {
|
if (!isValidEmail(emailStr)) {
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', `Некорректный формат email: ${emailStr}`);
|
throw new ApiError(400, 'VALIDATION_ERROR', `Некорректный формат email: ${emailStr}`);
|
||||||
}
|
}
|
||||||
if (passwordStr.length === 0) {
|
if (passwordStr.length === 0) {
|
||||||
@@ -39,7 +62,41 @@ function extractCredentials(rawBody: unknown): { email: string; password: string
|
|||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Пароль должен содержать минимум 8 символов');
|
throw new ApiError(400, 'VALIDATION_ERROR', 'Пароль должен содержать минимум 8 символов');
|
||||||
}
|
}
|
||||||
|
|
||||||
return { email: emailStr, password: passwordStr };
|
return { email: emailStr.toLowerCase(), password: passwordStr };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Создаёт пользователя и возвращает его с JWT-токеном.
|
||||||
|
* Race condition (параллельные регистрации с одним email) ловится
|
||||||
|
* unique-индексом Mongo (E11000) → 409 EMAIL_TAKEN.
|
||||||
|
*
|
||||||
|
* @param email — валидированный email
|
||||||
|
* @param password — пароль в открытом виде
|
||||||
|
* @returns 201-ответ { token, user: { id, email } }
|
||||||
|
*/
|
||||||
|
async function registerUser(res: Response, email: string, password: string): Promise<void> {
|
||||||
|
const passwordHash = await hashPassword(password);
|
||||||
|
|
||||||
|
let user;
|
||||||
|
try {
|
||||||
|
user = await User.create({ email, passwordHash });
|
||||||
|
} catch (err) {
|
||||||
|
// E11000 — duplicate key (параллельная регистрация того же email)
|
||||||
|
if (
|
||||||
|
err instanceof Error &&
|
||||||
|
'code' in err &&
|
||||||
|
(err as { code?: unknown }).code === 11000
|
||||||
|
) {
|
||||||
|
throw new ApiError(409, 'EMAIL_TAKEN', 'Пользователь с таким email уже существует');
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = signUserToken(user.id);
|
||||||
|
res.status(201).json({
|
||||||
|
token,
|
||||||
|
user: { id: user.id, email: user.email },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -61,22 +118,7 @@ const authRouter = Router();
|
|||||||
*/
|
*/
|
||||||
authRouter.post('/register', asyncHandler(async (req: Request, res: Response) => {
|
authRouter.post('/register', asyncHandler(async (req: Request, res: Response) => {
|
||||||
const { email, password } = extractCredentials(req.body);
|
const { email, password } = extractCredentials(req.body);
|
||||||
|
await registerUser(res, email, password);
|
||||||
// Проверяем, не существует ли пользователь с таким email
|
|
||||||
const existing = await User.findOne({ email });
|
|
||||||
if (existing) {
|
|
||||||
res.status(409).json({ error: { code: 'EMAIL_TAKEN', message: 'Пользователь с таким email уже существует' } });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const passwordHash = await hashPassword(password);
|
|
||||||
const user = await User.create({ email, passwordHash });
|
|
||||||
const token = signUserToken(user.id);
|
|
||||||
|
|
||||||
res.status(201).json({
|
|
||||||
token,
|
|
||||||
user: { id: user.id, email: user.email },
|
|
||||||
});
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -90,7 +132,7 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
|||||||
const { email, password } = extractCredentials(req.body);
|
const { email, password } = extractCredentials(req.body);
|
||||||
|
|
||||||
const user = await User.findOne({ email });
|
const user = await User.findOne({ email });
|
||||||
if (!user) {
|
if (user === null) {
|
||||||
res.status(401).json({ error: { code: 'INVALID_CREDENTIALS', message: 'Неверный email или пароль' } });
|
res.status(401).json({ error: { code: 'INVALID_CREDENTIALS', message: 'Неверный email или пароль' } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -112,19 +154,18 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
|||||||
* GET /api/auth/me
|
* GET /api/auth/me
|
||||||
*
|
*
|
||||||
* Возвращает данные авторизованного пользователя.
|
* Возвращает данные авторизованного пользователя.
|
||||||
* Требует Bearer-токен (auth middleware).
|
* Требует Bearer-токен (auth middleware, req.user установлен).
|
||||||
*
|
*
|
||||||
* @returns 200 { id, email }
|
* @returns 200 { id, email }
|
||||||
*/
|
*/
|
||||||
authRouter.get('/me', requireAuth, asyncHandler(async (req: Request, res: Response) => {
|
authRouter.get('/me', requireAuth, asyncHandler(async (req: Request, res: Response) => {
|
||||||
// req.user установлен requireAuth middleware
|
// req.user установлен requireAuth middleware (declaration merging)
|
||||||
const authedReq = req as AuthenticatedRequest;
|
if (req.user === undefined) {
|
||||||
if (authedReq.user === undefined) {
|
res.status(401).json({ error: { code: 'UNAUTHORIZED', message: AUTH_MSG } });
|
||||||
res.status(401).json({ error: { code: 'UNAUTHORIZED', message: 'Требуется авторизация' } });
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const user = await User.findById(authedReq.user.id);
|
const user = await User.findById(req.user.id);
|
||||||
if (!user) {
|
if (user === null) {
|
||||||
res.status(404).json({ error: { code: 'USER_NOT_FOUND', message: 'Пользователь не найден' } });
|
res.status(404).json({ error: { code: 'USER_NOT_FOUND', message: 'Пользователь не найден' } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
+232
-147
@@ -1,23 +1,23 @@
|
|||||||
import { Router, type Request, type Response } from 'express';
|
import { Router } from 'express';
|
||||||
|
|
||||||
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
import { requireAuth } from '../middleware/auth.middleware.js';
|
||||||
import News from '../models/news.model.js';
|
import News from '../models/news.model.js';
|
||||||
import { createNotification } from '../services/notification.service.js';
|
import { createNotification } from '../services/notification.service.js';
|
||||||
import { ApiError } from '../utils/ApiError.js';
|
import { ApiError } from '../utils/ApiError.js';
|
||||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||||
|
|
||||||
|
import type { Request, RequestHandler } from 'express';
|
||||||
import type { Server as SocketIOServer } from 'socket.io';
|
import type { Server as SocketIOServer } from 'socket.io';
|
||||||
|
|
||||||
|
/** Сообщение об ошибке авторизации. */
|
||||||
const AUTH_MSG = 'Требуется авторизация';
|
const AUTH_MSG = 'Требуется авторизация';
|
||||||
|
/** Сообщение об отсутствующей новости. */
|
||||||
const NOT_FOUND_MSG = 'Новость не найдена';
|
const NOT_FOUND_MSG = 'Новость не найдена';
|
||||||
|
|
||||||
/** Возвращает id авторизованного пользователя. */
|
/** Возвращает id из URL (req.params.id всегда строка в Express). */
|
||||||
function getUserId(req: Request): string {
|
function paramsId(req: Request): string {
|
||||||
const authedReq = req as AuthenticatedRequest;
|
const raw = req.params.id;
|
||||||
if (!authedReq.user) {
|
return Array.isArray(raw) ? raw[0] ?? '' : raw;
|
||||||
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
|
|
||||||
}
|
|
||||||
return authedReq.user.id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Безопасно извлекает поле из req.body. */
|
/** Безопасно извлекает поле из req.body. */
|
||||||
@@ -40,6 +40,222 @@ function serializeNews(n: InstanceType<typeof News>) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Возвращает id авторизованного пользователя (req.user установлен requireAuth).
|
||||||
|
*
|
||||||
|
* @param req — запрос Express
|
||||||
|
* @throws {ApiError} 401 если авторизация отсутствует
|
||||||
|
*/
|
||||||
|
function getUserId(req: Request): string {
|
||||||
|
const userId = req.user?.id;
|
||||||
|
if (userId === undefined) {
|
||||||
|
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
|
||||||
|
}
|
||||||
|
return userId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ищет новость автора или бросает 404 (ownership check).
|
||||||
|
*
|
||||||
|
* @param id — id новости из URL
|
||||||
|
* @param userId — id автора (из JWT)
|
||||||
|
* @returns найденный документ новости
|
||||||
|
*/
|
||||||
|
async function findNewsOfUser(id: string, userId: string): Promise<InstanceType<typeof News>> {
|
||||||
|
const news = await News.findOne({ _id: id, author: userId });
|
||||||
|
if (news === null) {
|
||||||
|
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||||
|
}
|
||||||
|
return news;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Валидирует title (не пуст, до 200 символов). */
|
||||||
|
function validateTitle(title: unknown): string {
|
||||||
|
if (typeof title !== 'string' || title.trim().length === 0) {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
|
||||||
|
}
|
||||||
|
if (title.trim().length > 200) {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', 'Название не должно превышать 200 символов');
|
||||||
|
}
|
||||||
|
return title.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Парсит и валидирует scheduledAt из тела запроса.
|
||||||
|
*
|
||||||
|
* @param raw — значение из req.body
|
||||||
|
* @returns валидированная дата в будущем
|
||||||
|
*/
|
||||||
|
function parseScheduledAt(raw: unknown): Date {
|
||||||
|
if (typeof raw !== 'string') {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть строкой (ISO-дата)');
|
||||||
|
}
|
||||||
|
const scheduledAt = new Date(raw);
|
||||||
|
if (Number.isNaN(scheduledAt.getTime())) {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt не является валидной датой');
|
||||||
|
}
|
||||||
|
if (scheduledAt.getTime() <= Date.now()) {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть в будущем');
|
||||||
|
}
|
||||||
|
return scheduledAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хендлер: GET /api/news — список новостей текущего пользователя.
|
||||||
|
*/
|
||||||
|
function handleListNews(): RequestHandler {
|
||||||
|
return asyncHandler(async (req, res) => {
|
||||||
|
const userId = getUserId(req);
|
||||||
|
const items = await News.find({ author: userId }).sort({ createdAt: -1 });
|
||||||
|
res.json({ news: items.map(serializeNews) });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хендлер: GET /api/news/:id — одна новость (только своя).
|
||||||
|
*/
|
||||||
|
function handleGetNews(): RequestHandler {
|
||||||
|
return asyncHandler(async (req, res) => {
|
||||||
|
const news = await findNewsOfUser(paramsId(req), getUserId(req));
|
||||||
|
res.json({ news: serializeNews(news) });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хендлер: POST /api/news — создание черновика.
|
||||||
|
*/
|
||||||
|
function handleCreateNews(): RequestHandler {
|
||||||
|
return asyncHandler(async (req, res) => {
|
||||||
|
const userId = getUserId(req);
|
||||||
|
const title = validateTitle(bodyField(req, 'title'));
|
||||||
|
const content = bodyField(req, 'content');
|
||||||
|
const news = await News.create({
|
||||||
|
title,
|
||||||
|
content: typeof content === 'string' ? content : '',
|
||||||
|
status: 'draft',
|
||||||
|
author: userId,
|
||||||
|
});
|
||||||
|
res.status(201).json({ news: serializeNews(news) });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хендлер: PATCH /api/news/:id — обновление title/content.
|
||||||
|
* Атомарный findOneAndUpdate (условие _id + author атомарно).
|
||||||
|
*/
|
||||||
|
function handleUpdateNews(): RequestHandler {
|
||||||
|
return asyncHandler(async (req, res) => {
|
||||||
|
const userId = getUserId(req);
|
||||||
|
const title = bodyField(req, 'title');
|
||||||
|
const content = bodyField(req, 'content');
|
||||||
|
|
||||||
|
const update: { $set: { title?: string; content?: string } } = { $set: {} };
|
||||||
|
if (title !== undefined) {
|
||||||
|
update.$set.title = validateTitle(title);
|
||||||
|
}
|
||||||
|
if (content !== undefined) {
|
||||||
|
if (typeof content !== 'string') {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', 'Контент должен быть строкой');
|
||||||
|
}
|
||||||
|
update.$set.content = content;
|
||||||
|
}
|
||||||
|
if (Object.keys(update.$set).length === 0) {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', 'Нечего обновлять: передайте title и/или content');
|
||||||
|
}
|
||||||
|
|
||||||
|
const news = await News.findOneAndUpdate(
|
||||||
|
{ _id: paramsId(req), author: userId },
|
||||||
|
update,
|
||||||
|
{ new: true },
|
||||||
|
);
|
||||||
|
if (news === null) {
|
||||||
|
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
||||||
|
}
|
||||||
|
res.json({ news: serializeNews(news) });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хендлер: DELETE /api/news/:id — удаление новости.
|
||||||
|
*
|
||||||
|
* @param io — Socket.IO server (необязательно; без него уведомление не шлётся)
|
||||||
|
*/
|
||||||
|
function handleDeleteNews(io?: SocketIOServer): RequestHandler {
|
||||||
|
return asyncHandler(async (req, res) => {
|
||||||
|
const userId = getUserId(req);
|
||||||
|
const news = await findNewsOfUser(paramsId(req), userId);
|
||||||
|
const title = news.title;
|
||||||
|
await news.deleteOne();
|
||||||
|
if (io !== undefined) {
|
||||||
|
await createNotification(io, {
|
||||||
|
user: userId, actor: userId, type: 'news.deleted',
|
||||||
|
newsId: paramsId(req),
|
||||||
|
title: 'Новость удалена',
|
||||||
|
message: `«${title}» была удалена`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
res.status(204).send();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хендлер: POST /api/news/:id/publish — немедленная публикация.
|
||||||
|
*
|
||||||
|
* @param io — Socket.IO server (необязательно)
|
||||||
|
*/
|
||||||
|
function handlePublishNews(io?: SocketIOServer): RequestHandler {
|
||||||
|
return asyncHandler(async (req, res) => {
|
||||||
|
const userId = getUserId(req);
|
||||||
|
const news = await findNewsOfUser(paramsId(req), userId);
|
||||||
|
if (news.status === 'published') {
|
||||||
|
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
|
||||||
|
}
|
||||||
|
news.status = 'published';
|
||||||
|
news.publishedAt = new Date();
|
||||||
|
news.scheduledAt = null;
|
||||||
|
await news.save();
|
||||||
|
if (io !== undefined) {
|
||||||
|
await createNotification(io, {
|
||||||
|
user: userId, actor: userId, type: 'news.published',
|
||||||
|
newsId: String(news._id),
|
||||||
|
title: 'Новость опубликована',
|
||||||
|
message: `«${news.title}» была опубликована`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
res.json({ news: serializeNews(news) });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хендлер: POST /api/news/:id/schedule — отложенная публикация.
|
||||||
|
*
|
||||||
|
* @param io — Socket.IO server (необязательно)
|
||||||
|
*/
|
||||||
|
function handleScheduleNews(io?: SocketIOServer): RequestHandler {
|
||||||
|
return asyncHandler(async (req, res) => {
|
||||||
|
const userId = getUserId(req);
|
||||||
|
const news = await findNewsOfUser(paramsId(req), userId);
|
||||||
|
if (news.status === 'published') {
|
||||||
|
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
|
||||||
|
}
|
||||||
|
|
||||||
|
const scheduledAt = parseScheduledAt(bodyField(req, 'scheduledAt'));
|
||||||
|
news.status = 'scheduled';
|
||||||
|
news.scheduledAt = scheduledAt;
|
||||||
|
news.publishedAt = null;
|
||||||
|
await news.save();
|
||||||
|
if (io !== undefined) {
|
||||||
|
await createNotification(io, {
|
||||||
|
user: userId, actor: userId, type: 'news.scheduled',
|
||||||
|
newsId: String(news._id),
|
||||||
|
title: 'Публикация запланирована',
|
||||||
|
message: `«${news.title}» запланирована на ${scheduledAt.toISOString()}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
res.json({ news: serializeNews(news) });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Создаёт news router с привязкой к Socket.IO серверу.
|
* Создаёт news router с привязкой к Socket.IO серверу.
|
||||||
*
|
*
|
||||||
@@ -50,144 +266,13 @@ export function createNewsRouter(io?: SocketIOServer): Router {
|
|||||||
const router = Router();
|
const router = Router();
|
||||||
router.use(requireAuth);
|
router.use(requireAuth);
|
||||||
|
|
||||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
router.get('/', handleListNews());
|
||||||
const userId = getUserId(req);
|
router.get('/:id', handleGetNews());
|
||||||
const items = await News.find({ author: userId }).sort({ createdAt: -1 });
|
router.post('/', handleCreateNews());
|
||||||
res.json({ news: items.map(serializeNews) });
|
router.patch('/:id', handleUpdateNews());
|
||||||
}));
|
router.delete('/:id', handleDeleteNews(io));
|
||||||
|
router.post('/:id/publish', handlePublishNews(io));
|
||||||
router.get('/:id', asyncHandler(async (req: Request, res: Response) => {
|
router.post('/:id/schedule', handleScheduleNews(io));
|
||||||
const userId = getUserId(req);
|
|
||||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
|
||||||
if (!news) {
|
|
||||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
|
||||||
}
|
|
||||||
res.json({ news: serializeNews(news) });
|
|
||||||
}));
|
|
||||||
|
|
||||||
router.post('/', asyncHandler(async (req: Request, res: Response) => {
|
|
||||||
const userId = getUserId(req);
|
|
||||||
const title = bodyField(req, 'title');
|
|
||||||
const content = bodyField(req, 'content');
|
|
||||||
if (typeof title !== 'string' || title.trim().length === 0) {
|
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
|
|
||||||
}
|
|
||||||
if (title.trim().length > 200) {
|
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название не должно превышать 200 символов');
|
|
||||||
}
|
|
||||||
const news = await News.create({
|
|
||||||
title: title.trim(),
|
|
||||||
content: typeof content === 'string' ? content : '',
|
|
||||||
status: 'draft',
|
|
||||||
author: userId,
|
|
||||||
});
|
|
||||||
res.status(201).json({ news: serializeNews(news) });
|
|
||||||
}));
|
|
||||||
|
|
||||||
router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
|
|
||||||
const userId = getUserId(req);
|
|
||||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
|
||||||
if (!news) {
|
|
||||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
|
||||||
}
|
|
||||||
const title = bodyField(req, 'title');
|
|
||||||
const content = bodyField(req, 'content');
|
|
||||||
if (title !== undefined) {
|
|
||||||
if (typeof title !== 'string' || title.trim().length === 0) {
|
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
|
|
||||||
}
|
|
||||||
if (title.trim().length > 200) {
|
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Название не должно превышать 200 символов');
|
|
||||||
}
|
|
||||||
news.title = title.trim();
|
|
||||||
}
|
|
||||||
if (content !== undefined) {
|
|
||||||
if (typeof content !== 'string') {
|
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Контент должен быть строкой');
|
|
||||||
}
|
|
||||||
news.content = content;
|
|
||||||
}
|
|
||||||
await news.save();
|
|
||||||
res.json({ news: serializeNews(news) });
|
|
||||||
}));
|
|
||||||
|
|
||||||
router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
|
|
||||||
const userId = getUserId(req);
|
|
||||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
|
||||||
if (!news) {
|
|
||||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
|
||||||
}
|
|
||||||
const title = news.title;
|
|
||||||
await news.deleteOne();
|
|
||||||
if (io) {
|
|
||||||
await createNotification(io, {
|
|
||||||
user: userId, actor: userId, type: 'news.deleted',
|
|
||||||
newsId: String(req.params.id),
|
|
||||||
title: 'Новость удалена',
|
|
||||||
message: `«${title}» была удалена`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
res.status(204).send();
|
|
||||||
}));
|
|
||||||
|
|
||||||
router.post('/:id/publish', asyncHandler(async (req: Request, res: Response) => {
|
|
||||||
const userId = getUserId(req);
|
|
||||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
|
||||||
if (!news) {
|
|
||||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
|
||||||
}
|
|
||||||
if (news.status === 'published') {
|
|
||||||
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
|
|
||||||
}
|
|
||||||
news.status = 'published';
|
|
||||||
news.publishedAt = new Date();
|
|
||||||
news.scheduledAt = null;
|
|
||||||
await news.save();
|
|
||||||
if (io) {
|
|
||||||
await createNotification(io, {
|
|
||||||
user: userId, actor: userId, type: 'news.published',
|
|
||||||
newsId: String(news._id),
|
|
||||||
title: 'Новость опубликована',
|
|
||||||
message: `«${news.title}» была опубликована`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
res.json({ news: serializeNews(news) });
|
|
||||||
}));
|
|
||||||
|
|
||||||
router.post('/:id/schedule', asyncHandler(async (req: Request, res: Response) => {
|
|
||||||
const userId = getUserId(req);
|
|
||||||
const news = await News.findOne({ _id: req.params.id, author: userId });
|
|
||||||
if (!news) {
|
|
||||||
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
|
|
||||||
}
|
|
||||||
if (news.status === 'published') {
|
|
||||||
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
|
|
||||||
}
|
|
||||||
const scheduledAtRaw = bodyField(req, 'scheduledAt');
|
|
||||||
if (typeof scheduledAtRaw !== 'string') {
|
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть строкой (ISO-дата)');
|
|
||||||
}
|
|
||||||
const scheduledAt = new Date(scheduledAtRaw);
|
|
||||||
if (Number.isNaN(scheduledAt.getTime())) {
|
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt не является валидной датой');
|
|
||||||
}
|
|
||||||
if (scheduledAt.getTime() <= Date.now()) {
|
|
||||||
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть в будущем');
|
|
||||||
}
|
|
||||||
news.status = 'scheduled';
|
|
||||||
news.scheduledAt = scheduledAt;
|
|
||||||
news.publishedAt = null;
|
|
||||||
await news.save();
|
|
||||||
if (io) {
|
|
||||||
await createNotification(io, {
|
|
||||||
user: userId, actor: userId, type: 'news.scheduled',
|
|
||||||
newsId: String(news._id),
|
|
||||||
title: 'Публикация запланирована',
|
|
||||||
message: `«${news.title}» запланирована на ${scheduledAt.toISOString()}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
res.json({ news: serializeNews(news) });
|
|
||||||
}));
|
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,38 @@
|
|||||||
import { Router, type Request, type Response } from 'express';
|
import { Router } from 'express';
|
||||||
|
|
||||||
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
import { requireAuth } from '../middleware/auth.middleware.js';
|
||||||
import Notification from '../models/notification.model.js';
|
import Notification from '../models/notification.model.js';
|
||||||
import { ApiError } from '../utils/ApiError.js';
|
import { ApiError } from '../utils/ApiError.js';
|
||||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||||
|
|
||||||
|
import type { Request, Response } from 'express';
|
||||||
|
|
||||||
|
/** Сообщение об ошибке авторизации. */
|
||||||
|
const AUTH_MSG = 'Требуется авторизация';
|
||||||
|
|
||||||
const notificationRouter = Router();
|
const notificationRouter = Router();
|
||||||
|
|
||||||
// Все маршруты требуют авторизацию
|
// Все маршруты требуют авторизацию (req.user — declaration merging)
|
||||||
notificationRouter.use(requireAuth);
|
notificationRouter.use(requireAuth);
|
||||||
|
|
||||||
|
/** Возвращает id из URL (req.params.id всегда строка в Express). */
|
||||||
|
function paramsId(req: Request): string {
|
||||||
|
const raw = req.params.id;
|
||||||
|
return Array.isArray(raw) ? raw[0] ?? '' : raw;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Извлекает id пользователя из авторизованного запроса.
|
* Возвращает id авторизованного пользователя или бросает 401.
|
||||||
*
|
*
|
||||||
* @param req — запрос Express
|
* @param req — запрос Express
|
||||||
* @returns id пользователя
|
* @returns id пользователя
|
||||||
*/
|
*/
|
||||||
function getUserId(req: Request): string {
|
function getUserId(req: Request): string {
|
||||||
const authedReq = req as AuthenticatedRequest;
|
const userId = req.user?.id;
|
||||||
if (!authedReq.user) {
|
if (userId === undefined) {
|
||||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
|
||||||
}
|
}
|
||||||
return authedReq.user.id;
|
return userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -87,8 +98,8 @@ notificationRouter.patch(
|
|||||||
'/:id/read',
|
'/:id/read',
|
||||||
asyncHandler(async (req: Request, res: Response) => {
|
asyncHandler(async (req: Request, res: Response) => {
|
||||||
const userId = getUserId(req);
|
const userId = getUserId(req);
|
||||||
const notification = await Notification.findOne({ _id: req.params.id, user: userId });
|
const notification = await Notification.findOne({ _id: paramsId(req), user: userId });
|
||||||
if (!notification) {
|
if (notification === null) {
|
||||||
throw new ApiError(404, 'NOTIFICATION_NOT_FOUND', 'Уведомление не найдено');
|
throw new ApiError(404, 'NOTIFICATION_NOT_FOUND', 'Уведомление не найдено');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,19 @@
|
|||||||
import { Router, type Request, type Response } from 'express';
|
import { Router } from 'express';
|
||||||
|
|
||||||
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
import { requireAuth } from '../middleware/auth.middleware.js';
|
||||||
import { upload } from '../middleware/upload.middleware.js';
|
import { upload } from '../middleware/upload.middleware.js';
|
||||||
import { ApiError } from '../utils/ApiError.js';
|
import { ApiError } from '../utils/ApiError.js';
|
||||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||||
|
|
||||||
|
import type { Request, Response } from 'express';
|
||||||
|
|
||||||
const uploadRouter = Router();
|
const uploadRouter = Router();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Обёртка для multer: конвертирует multer errors в ApiError (400/413).
|
* Обёртка для multer: конвертирует multer errors в ApiError (400/413).
|
||||||
|
*
|
||||||
|
* @param fileFilter — имя поля файла (multer)
|
||||||
|
* @returns middleware Express
|
||||||
*/
|
*/
|
||||||
function multerHandler(fileFilter: 'file') {
|
function multerHandler(fileFilter: 'file') {
|
||||||
return (req: Request, res: Response, next: (err?: unknown) => void): void => {
|
return (req: Request, res: Response, next: (err?: unknown) => void): void => {
|
||||||
@@ -42,13 +47,13 @@ uploadRouter.post(
|
|||||||
requireAuth,
|
requireAuth,
|
||||||
multerHandler('file'),
|
multerHandler('file'),
|
||||||
asyncHandler(async (req: Request, res: Response) => {
|
asyncHandler(async (req: Request, res: Response) => {
|
||||||
const authedReq = req as AuthenticatedRequest;
|
const userId = req.user?.id;
|
||||||
if (!authedReq.user) {
|
if (userId === undefined) {
|
||||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Multer устанавливает req.file при успешной загрузке
|
// Multer устанавливает req.file при успешной загрузке
|
||||||
if (!req.file) {
|
if (req.file === undefined) {
|
||||||
throw new ApiError(400, 'NO_FILE', 'Файл не был загружен');
|
throw new ApiError(400, 'NO_FILE', 'Файл не был загружен');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+35
-7
@@ -1,32 +1,51 @@
|
|||||||
import http from 'node:http';
|
import http from 'node:http';
|
||||||
|
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
import { createApp } from './app.js';
|
import { createApp } from './app.js';
|
||||||
import { connectDatabase } from './config/database.js';
|
import { connectDatabase } from './config/database.js';
|
||||||
import { env } from './config/env.js';
|
import { env } from './config/env.js';
|
||||||
import { startPublicationScheduler, stopPublicationScheduler } from './services/publicationScheduler.service.js';
|
import { startPublicationScheduler, stopPublicationScheduler } from './services/publicationScheduler.service.js';
|
||||||
import { createSocketServer } from './socket/socketServer.js';
|
import { createSocketServer } from './socket/socketServer.js';
|
||||||
|
|
||||||
|
/** Таймаут принудительного завершения, если соединения не закрылись. */
|
||||||
|
const SHUTDOWN_TIMEOUT_MS = 10_000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Завершает работу процесса после закрытия сервера.
|
* Корректно завершает работу: scheduler → mongoose → HTTP-сервер.
|
||||||
|
* Если незакрытые соединения не освобождаются за SHUTDOWN_TIMEOUT_MS —
|
||||||
|
* процесс принудительно завершается с кодом 1.
|
||||||
*
|
*
|
||||||
* @param signal — сигнал, по которому остановлен процесс
|
* @param signal — сигнал, по которому остановлен процесс
|
||||||
* @param server — HTTP-сервер для закрытия
|
* @param server — HTTP-сервер для закрытия
|
||||||
*/
|
*/
|
||||||
function shutdown(signal: string, server: http.Server): void {
|
function shutdown(signal: string, server: http.Server): void {
|
||||||
console.warn(`Сигнал ${signal} получен, завершение работы...`);
|
console.warn(`Сигнал ${signal} получен, завершение работы...`);
|
||||||
|
|
||||||
|
const forceExit = setTimeout(() => {
|
||||||
|
console.error(`Не удалось завершить за ${String(SHUTDOWN_TIMEOUT_MS)} мс, принудительный выход`);
|
||||||
|
process.exit(1);
|
||||||
|
}, SHUTDOWN_TIMEOUT_MS);
|
||||||
|
forceExit.unref();
|
||||||
|
|
||||||
stopPublicationScheduler();
|
stopPublicationScheduler();
|
||||||
|
|
||||||
|
mongoose.connection.close()
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
console.error('Ошибка при закрытии MongoDB:', err);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
server.close(() => {
|
server.close(() => {
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Точка входа приложения.
|
* Точка входа приложения.
|
||||||
*
|
*
|
||||||
* Подключает MongoDB, создаёт HTTP-сервер, Socket.IO и Express, запускает scheduler.
|
* Подключает MongoDB, создаёт HTTP-сервер, Socket.IO и Express, запускает scheduler.
|
||||||
*
|
|
||||||
* Socket.IO подключается к HTTP-серверу через engine.io (перехватывает /socket.io).
|
* Socket.IO подключается к HTTP-серверу через engine.io (перехватывает /socket.io).
|
||||||
* Express не отвечает на /socket.io (middleware в app.ts) — Socket.IO обрабатывает.
|
|
||||||
*/
|
*/
|
||||||
async function main(): Promise<void> {
|
async function main(): Promise<void> {
|
||||||
await connectDatabase();
|
await connectDatabase();
|
||||||
@@ -37,13 +56,12 @@ async function main(): Promise<void> {
|
|||||||
// Socket.IO подключается к HTTP-серверу (engine.io перехватывает /socket.io)
|
// Socket.IO подключается к HTTP-серверу (engine.io перехватывает /socket.io)
|
||||||
const io = createSocketServer(server);
|
const io = createSocketServer(server);
|
||||||
|
|
||||||
// Express-приложение (с io для news routes)
|
// Express-приложение (с io для news routes и scheduler)
|
||||||
// Express НЕ отвечает на /socket.io — middleware в app.ts
|
|
||||||
const app = createApp({ io });
|
const app = createApp({ io });
|
||||||
server.on('request', app);
|
server.on('request', app);
|
||||||
|
|
||||||
// Запускаем планировщик отложенной публикации
|
// Запускаем планировщик отложенной публикации (с io для real-time уведомлений)
|
||||||
startPublicationScheduler(env.schedulerIntervalMs);
|
startPublicationScheduler(env.schedulerIntervalMs, io);
|
||||||
|
|
||||||
server.listen(env.port, () => {
|
server.listen(env.port, () => {
|
||||||
console.warn(`News Editor API запущен на порту ${String(env.port)} (${env.nodeEnv})`);
|
console.warn(`News Editor API запущен на порту ${String(env.port)} (${env.nodeEnv})`);
|
||||||
@@ -56,6 +74,16 @@ async function main(): Promise<void> {
|
|||||||
process.on('SIGTERM', () => {
|
process.on('SIGTERM', () => {
|
||||||
shutdown('SIGTERM', server);
|
shutdown('SIGTERM', server);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Несюретный reject / исключение — логируем и graceful shutdown (Node 15+ иначе убьёт процесс)
|
||||||
|
process.on('unhandledRejection', (reason: unknown) => {
|
||||||
|
console.error('Unhandled rejection:', reason);
|
||||||
|
shutdown('unhandledRejection', server);
|
||||||
|
});
|
||||||
|
process.on('uncaughtException', (err: unknown) => {
|
||||||
|
console.error('Uncaught exception:', err);
|
||||||
|
shutdown('uncaughtException', server);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void main().catch((err: unknown) => {
|
void main().catch((err: unknown) => {
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ import type { Server as SocketIOServer } from 'socket.io';
|
|||||||
|
|
||||||
/** Параметры для создания уведомления. */
|
/** Параметры для создания уведомления. */
|
||||||
interface CreateNotificationParams {
|
interface CreateNotificationParams {
|
||||||
/** Пользователь-получатель. */
|
/** Пользователь-получатель (ObjectId). */
|
||||||
user: string;
|
user: string;
|
||||||
/** Пользователь-инициатор действия. */
|
/** Пользователь-инициатор действия (ObjectId, может совпадать с user). */
|
||||||
actor: string;
|
actor: string;
|
||||||
/** Тип события. */
|
/** Тип события. */
|
||||||
type: NotificationType;
|
type: NotificationType;
|
||||||
@@ -23,18 +23,14 @@ interface CreateNotificationParams {
|
|||||||
* Сохраняет уведомление в БД и отправляет real-time событие через Socket.IO.
|
* Сохраняет уведомление в БД и отправляет real-time событие через Socket.IO.
|
||||||
*
|
*
|
||||||
* @param io — экземпляр Socket.IO server
|
* @param io — экземпляр Socket.IO server
|
||||||
* @param params — данные уведомления
|
* @param params — данные уведомления (user/actor — ObjectId-строки,
|
||||||
* @returns сохранённое уведомление (или null, если получатель = автор — не уведомляем себя)
|
* Mongoose кастит их в ObjectId)
|
||||||
*/
|
*/
|
||||||
export async function createNotification(
|
export async function createNotification(
|
||||||
io: SocketIOServer,
|
io: SocketIOServer,
|
||||||
params: CreateNotificationParams,
|
params: CreateNotificationParams,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// Не уведомляем пользователя о собственных действиях
|
// Mongoose кастит string → ObjectId (user/actor/newsId)
|
||||||
if (params.user === params.actor) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const notification = await Notification.create({
|
const notification = await Notification.create({
|
||||||
user: params.user,
|
user: params.user,
|
||||||
actor: params.actor,
|
actor: params.actor,
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import News from '../models/news.model.js';
|
import News from '../models/news.model.js';
|
||||||
|
|
||||||
|
import { createNotification } from './notification.service.js';
|
||||||
|
|
||||||
|
import type { Server as SocketIOServer } from 'socket.io';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Публикационный планировщик (MongoDB-backed poll).
|
* Публикационный планировщик (MongoDB-backed poll).
|
||||||
*
|
*
|
||||||
@@ -10,18 +14,32 @@ import News from '../models/news.model.js';
|
|||||||
* Не использует setTimeout на конкретную статью — только poll.
|
* Не использует setTimeout на конкретную статью — только poll.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/** Минимальное окно поиска недавно опубликованных (защита от часовых сдвигов). */
|
||||||
|
const MIN_SCAN_WINDOW_MS = 60_000;
|
||||||
|
const DEFAULT_INTERVAL_MS = 20_000;
|
||||||
|
|
||||||
let timer: ReturnType<typeof setInterval> | null = null;
|
let timer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let ioRef: SocketIOServer | null = null;
|
||||||
|
let currentIntervalMs = DEFAULT_INTERVAL_MS;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Запускает периодический poll для автоматической публикации.
|
* Запускает периодический poll для автоматической публикации.
|
||||||
*
|
*
|
||||||
* @param intervalMs — интервал опроса в мс (по умолчанию 20000 = 20 сек)
|
* @param intervalMs — интервал опроса в мс (по умолчанию 20000 = 20 сек)
|
||||||
|
* @param io — Socket.IO server для real-time уведомлений (необязательно)
|
||||||
* @returns void
|
* @returns void
|
||||||
*/
|
*/
|
||||||
export function startPublicationScheduler(intervalMs = 20_000): void {
|
export function startPublicationScheduler(
|
||||||
|
intervalMs = DEFAULT_INTERVAL_MS,
|
||||||
|
io?: SocketIOServer,
|
||||||
|
): void {
|
||||||
if (timer) {
|
if (timer) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (io !== undefined) {
|
||||||
|
ioRef = io;
|
||||||
|
}
|
||||||
|
currentIntervalMs = intervalMs;
|
||||||
|
|
||||||
const poll = async (): Promise<void> => {
|
const poll = async (): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
@@ -35,9 +53,10 @@ export function startPublicationScheduler(intervalMs = 20_000): void {
|
|||||||
|
|
||||||
if (result.modifiedCount > 0) {
|
if (result.modifiedCount > 0) {
|
||||||
console.log(`[scheduler] Опубликовано новостей: ${String(result.modifiedCount)}`);
|
console.log(`[scheduler] Опубликовано новостей: ${String(result.modifiedCount)}`);
|
||||||
|
// Уведомляем авторов об автоматической публикации
|
||||||
|
await notifyPublishedAuthors(now);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
||||||
console.error('[scheduler] Ошибка при публикации:', err);
|
console.error('[scheduler] Ошибка при публикации:', err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -56,6 +75,41 @@ export function startPublicationScheduler(intervalMs = 20_000): void {
|
|||||||
timer.unref();
|
timer.unref();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Находит новости, только что опубликованные планировщиком,
|
||||||
|
* и создаёт для каждого автора уведомление + real-time событие.
|
||||||
|
*
|
||||||
|
* Окно поиска — интервал опроса + запас: publishedAt был установлен
|
||||||
|
* этим (или предыдущим) poll'ом, scheduledAt обнулился.
|
||||||
|
*
|
||||||
|
* @param now — момент публикации (из updateMany)
|
||||||
|
*/
|
||||||
|
async function notifyPublishedAuthors(now: Date): Promise<void> {
|
||||||
|
const windowMs = Math.max(currentIntervalMs, MIN_SCAN_WINDOW_MS) * 2;
|
||||||
|
const since = new Date(now.getTime() - windowMs);
|
||||||
|
|
||||||
|
const published = await News.find({
|
||||||
|
status: 'published',
|
||||||
|
publishedAt: { $gte: since },
|
||||||
|
scheduledAt: { $eq: null },
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const news of published) {
|
||||||
|
const io = ioRef;
|
||||||
|
if (io === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await createNotification(io, {
|
||||||
|
user: String(news.author),
|
||||||
|
actor: String(news.author),
|
||||||
|
type: 'news.published',
|
||||||
|
newsId: String(news._id),
|
||||||
|
title: 'Новость опубликована',
|
||||||
|
message: `«${news.title}» была опубликована (отложенная публикация)`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Останавливает планировщик (для тестов и graceful shutdown).
|
* Останавливает планировщик (для тестов и graceful shutdown).
|
||||||
*/
|
*/
|
||||||
@@ -64,4 +118,5 @@ export function stopPublicationScheduler(): void {
|
|||||||
clearInterval(timer);
|
clearInterval(timer);
|
||||||
timer = null;
|
timer = null;
|
||||||
}
|
}
|
||||||
|
ioRef = null;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+23
@@ -0,0 +1,23 @@
|
|||||||
|
/**
|
||||||
|
* Расширение типов Express: `req.user` устанавливается auth middleware
|
||||||
|
* (requireAuth) после успешной верификации JWT.
|
||||||
|
*
|
||||||
|
* @types/express-serve-static-core объявляет глобальный интерфейс
|
||||||
|
* `Express.Request` — в него добавляется поле `user` (declaration merging),
|
||||||
|
* чтобы `req.user` был доступен во всех route без type-assertions.
|
||||||
|
*
|
||||||
|
* Файл должен остаться "module" (есть import), иначе `declare global`
|
||||||
|
* не сработает — поэтому используется `import type` + `export {}`.
|
||||||
|
*/
|
||||||
|
import type {} from 'express-serve-static-core';
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
namespace Express {
|
||||||
|
interface Request {
|
||||||
|
/** Данные авторизованного пользователя (id из JWT payload). */
|
||||||
|
user?: { id: string };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export {};
|
||||||
+11
-18
@@ -1,19 +1,8 @@
|
|||||||
import jwt from 'jsonwebtoken';
|
import { sign, verify, type SignOptions } from 'jsonwebtoken';
|
||||||
|
|
||||||
import { env } from '../config/env.js';
|
import { env } from '../config/env.js';
|
||||||
|
|
||||||
import type { SignOptions } from 'jsonwebtoken';
|
import type { StringValue } from 'ms';
|
||||||
|
|
||||||
/**
|
|
||||||
* Payload JWT-токена.
|
|
||||||
*
|
|
||||||
* @property id — ObjectId пользователя (обязателен по ТЗ)
|
|
||||||
* @property sub — subject, дублирует id для совместимости
|
|
||||||
*/
|
|
||||||
export interface JwtPayload {
|
|
||||||
readonly id: string;
|
|
||||||
readonly sub: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Подписывает JWT-токен для пользователя с настройками из env.
|
* Подписывает JWT-токен для пользователя с настройками из env.
|
||||||
@@ -22,9 +11,13 @@ export interface JwtPayload {
|
|||||||
* @returns подписанный токен
|
* @returns подписанный токен
|
||||||
*/
|
*/
|
||||||
export function signUserToken(userId: string): string {
|
export function signUserToken(userId: string): string {
|
||||||
const payload: Omit<JwtPayload, 'iat' | 'exp'> = { id: userId, sub: userId };
|
// Payload по ТЗ: id обязателен, sub дублирует id для совместимости
|
||||||
const options: SignOptions = { expiresIn: 7 * 24 * 60 * 60 };
|
const payload = { id: userId, sub: userId };
|
||||||
const token = jwt.sign(payload, env.jwtSecret, options);
|
// Срок жизни берём из env (JWT_EXPIRES_IN, по умолчанию 7d).
|
||||||
|
// StringValue из пакета ms — тип, который принимает expiresIn;
|
||||||
|
// double-assertion: env — string, а @types/jsonwebtoken ожидает ms-тип.
|
||||||
|
const options: SignOptions = { expiresIn: env.jwtExpiresIn as unknown as StringValue };
|
||||||
|
const token = sign(payload, env.jwtSecret, options);
|
||||||
return typeof token === 'string' ? token : '';
|
return typeof token === 'string' ? token : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,8 +27,8 @@ export function signUserToken(userId: string): string {
|
|||||||
* @param token — токен (без префикса Bearer)
|
* @param token — токен (без префикса Bearer)
|
||||||
* @returns payload токена
|
* @returns payload токена
|
||||||
*/
|
*/
|
||||||
export function verifyUserToken(token: string): JwtPayload {
|
export function verifyUserToken(token: string): { id: string; sub: string } {
|
||||||
const decoded = jwt.verify(token, env.jwtSecret);
|
const decoded = verify(token, env.jwtSecret);
|
||||||
if (typeof decoded === 'string') {
|
if (typeof decoded === 'string') {
|
||||||
throw new Error('Неожиданный формат JWT payload');
|
throw new Error('Неожиданный формат JWT payload');
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user