Ревью кода: исправление найденных проблем
This commit is contained in:
+11
-1
@@ -300,9 +300,19 @@ export default defineConfig(
|
||||
'@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',
|
||||
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: {
|
||||
// express.static, jwt.sign/verify, multer.diskStorage — default export API
|
||||
'import-x/no-named-as-default-member': 'off',
|
||||
|
||||
@@ -33,13 +33,6 @@ export function createApp(options?: CreateAppOptions): express.Express {
|
||||
const app = express();
|
||||
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
|
||||
app.use(helmet());
|
||||
|
||||
|
||||
@@ -87,6 +87,51 @@ function parseMaxUploadSize(raw: string): number {
|
||||
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} если отсутствуют обязательные переменные или значения некорректны
|
||||
*/
|
||||
export function loadEnv(): Env {
|
||||
const uploadDirRaw = process.env.UPLOAD_DIR ?? 'uploads';
|
||||
const uploadDir = path.isAbsolute(uploadDirRaw)
|
||||
? uploadDirRaw
|
||||
: path.join(SERVER_ROOT, uploadDirRaw);
|
||||
const clientOrigin = process.env.CLIENT_ORIGIN ?? 'http://localhost:5173';
|
||||
|
||||
return {
|
||||
nodeEnv: process.env.NODE_ENV ?? 'development',
|
||||
@@ -105,11 +147,11 @@ export function loadEnv(): Env {
|
||||
mongoUri: required('MONGODB_URI'),
|
||||
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,
|
||||
clientOrigin,
|
||||
clientOrigins: clientOrigin.split(',').map((s) => s.trim()),
|
||||
uploadDir: parseUploadDir(process.env.UPLOAD_DIR ?? 'uploads'),
|
||||
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';
|
||||
|
||||
/**
|
||||
* Расширенный запрос с данными авторизованного пользователя.
|
||||
*
|
||||
* Устанавливается auth middleware после успешной верификации Bearer-токена.
|
||||
*/
|
||||
export interface AuthenticatedRequest extends Request {
|
||||
user?: { id: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware авторизации.
|
||||
*
|
||||
* Читает заголовок `Authorization: Bearer <token>`, верифицирует JWT
|
||||
* и устанавливает `req.user.id` для последующих обработчиков.
|
||||
* и устанавливает `req.user.id` для последующих обработчиков
|
||||
* (req.user расширен declaration merging в types/express.d.ts).
|
||||
* При отсутствии или невалидном токене — бросает ApiError 401.
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @param res — ответ Express
|
||||
* @param _res — ответ Express
|
||||
* @param next — функция продолжения цепочки middleware
|
||||
*/
|
||||
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 {
|
||||
const payload = verifyUserToken(token);
|
||||
(req as AuthenticatedRequest).user = { id: payload.id };
|
||||
req.user = { id: payload.id };
|
||||
next();
|
||||
} catch {
|
||||
next(new ApiError(401, 'UNAUTHORIZED', 'Невалидный или истёкший токен'));
|
||||
|
||||
@@ -48,8 +48,6 @@ const newsSchema = new Schema<INews>(
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
toJSON: { virtuals: true },
|
||||
toObject: { virtuals: true },
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ const notificationSchema = new Schema<INotification>(
|
||||
actor: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
// Могут совпадать с user (однопользовательский сценарий) или
|
||||
// быть null (системные уведомления). Mongoose кастит string → ObjectId.
|
||||
default: null,
|
||||
},
|
||||
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 createdAt / updatedAt — автоматические timestamps
|
||||
*
|
||||
* Примечание: нормализация email (trim/lowercase) выполняется один раз
|
||||
* в auth.routes.ts (extractCredentials) — schema не дублирует её.
|
||||
*/
|
||||
const userSchema = new mongoose.Schema<IUser>(
|
||||
{
|
||||
@@ -26,8 +30,6 @@ const userSchema = new mongoose.Schema<IUser>(
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
lowercase: true,
|
||||
trim: true,
|
||||
},
|
||||
passwordHash: {
|
||||
type: String,
|
||||
@@ -67,7 +69,3 @@ export async function hashPassword(password: string): Promise<string> {
|
||||
export async function comparePassword(password: string, hashValue: string): Promise<boolean> {
|
||||
return compare(password, hashValue);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,12 +6,35 @@ import { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
import { signUserToken } from '../utils/jwt.js';
|
||||
|
||||
import type { AuthenticatedRequest } from '../middleware/auth.middleware.js';
|
||||
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 (trim + lowercase) выполняется один раз здесь —
|
||||
* в схеме Mongoose не дублируется.
|
||||
*
|
||||
* @param rawBody — тело запроса (any из Express)
|
||||
* @returns объект с валидированными email и password
|
||||
* @throws {ApiError} с конкретным сообщением о проблеме
|
||||
@@ -23,13 +46,13 @@ function extractCredentials(rawBody: unknown): { email: string; password: string
|
||||
const record = rawBody as Record<string, unknown>;
|
||||
const email = record.email;
|
||||
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 : '';
|
||||
|
||||
if (emailStr.length === 0) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Email не указан');
|
||||
}
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailStr)) {
|
||||
if (!isValidEmail(emailStr)) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', `Некорректный формат email: ${emailStr}`);
|
||||
}
|
||||
if (passwordStr.length === 0) {
|
||||
@@ -39,7 +62,41 @@ function extractCredentials(rawBody: unknown): { email: string; password: string
|
||||
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) => {
|
||||
const { email, password } = extractCredentials(req.body);
|
||||
|
||||
// Проверяем, не существует ли пользователь с таким 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 },
|
||||
});
|
||||
await registerUser(res, email, password);
|
||||
}));
|
||||
|
||||
/**
|
||||
@@ -90,7 +132,7 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
||||
const { email, password } = extractCredentials(req.body);
|
||||
|
||||
const user = await User.findOne({ email });
|
||||
if (!user) {
|
||||
if (user === null) {
|
||||
res.status(401).json({ error: { code: 'INVALID_CREDENTIALS', message: 'Неверный email или пароль' } });
|
||||
return;
|
||||
}
|
||||
@@ -112,19 +154,18 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
||||
* GET /api/auth/me
|
||||
*
|
||||
* Возвращает данные авторизованного пользователя.
|
||||
* Требует Bearer-токен (auth middleware).
|
||||
* Требует Bearer-токен (auth middleware, req.user установлен).
|
||||
*
|
||||
* @returns 200 { id, email }
|
||||
*/
|
||||
authRouter.get('/me', requireAuth, asyncHandler(async (req: Request, res: Response) => {
|
||||
// req.user установлен requireAuth middleware
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
if (authedReq.user === undefined) {
|
||||
res.status(401).json({ error: { code: 'UNAUTHORIZED', message: 'Требуется авторизация' } });
|
||||
// req.user установлен requireAuth middleware (declaration merging)
|
||||
if (req.user === undefined) {
|
||||
res.status(401).json({ error: { code: 'UNAUTHORIZED', message: AUTH_MSG } });
|
||||
return;
|
||||
}
|
||||
const user = await User.findById(authedReq.user.id);
|
||||
if (!user) {
|
||||
const user = await User.findById(req.user.id);
|
||||
if (user === null) {
|
||||
res.status(404).json({ error: { code: 'USER_NOT_FOUND', message: 'Пользователь не найден' } });
|
||||
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 { createNotification } from '../services/notification.service.js';
|
||||
import { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
import type { Request, RequestHandler } from 'express';
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/** Сообщение об ошибке авторизации. */
|
||||
const AUTH_MSG = 'Требуется авторизация';
|
||||
/** Сообщение об отсутствующей новости. */
|
||||
const NOT_FOUND_MSG = 'Новость не найдена';
|
||||
|
||||
/** Возвращает id авторизованного пользователя. */
|
||||
function getUserId(req: Request): string {
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
if (!authedReq.user) {
|
||||
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
|
||||
}
|
||||
return authedReq.user.id;
|
||||
/** Возвращает id из URL (req.params.id всегда строка в Express). */
|
||||
function paramsId(req: Request): string {
|
||||
const raw = req.params.id;
|
||||
return Array.isArray(raw) ? raw[0] ?? '' : raw;
|
||||
}
|
||||
|
||||
/** Безопасно извлекает поле из 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 серверу.
|
||||
*
|
||||
@@ -50,144 +266,13 @@ export function createNewsRouter(io?: SocketIOServer): Router {
|
||||
const router = Router();
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get('/', asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const items = await News.find({ author: userId }).sort({ createdAt: -1 });
|
||||
res.json({ news: items.map(serializeNews) });
|
||||
}));
|
||||
|
||||
router.get('/: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);
|
||||
}
|
||||
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) });
|
||||
}));
|
||||
router.get('/', handleListNews());
|
||||
router.get('/:id', handleGetNews());
|
||||
router.post('/', handleCreateNews());
|
||||
router.patch('/:id', handleUpdateNews());
|
||||
router.delete('/:id', handleDeleteNews(io));
|
||||
router.post('/:id/publish', handlePublishNews(io));
|
||||
router.post('/:id/schedule', handleScheduleNews(io));
|
||||
|
||||
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 { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
/** Сообщение об ошибке авторизации. */
|
||||
const AUTH_MSG = 'Требуется авторизация';
|
||||
|
||||
const notificationRouter = Router();
|
||||
|
||||
// Все маршруты требуют авторизацию
|
||||
// Все маршруты требуют авторизацию (req.user — declaration merging)
|
||||
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
|
||||
* @returns id пользователя
|
||||
*/
|
||||
function getUserId(req: Request): string {
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
if (!authedReq.user) {
|
||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
||||
const userId = req.user?.id;
|
||||
if (userId === undefined) {
|
||||
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
|
||||
}
|
||||
return authedReq.user.id;
|
||||
return userId;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,8 +98,8 @@ notificationRouter.patch(
|
||||
'/:id/read',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const notification = await Notification.findOne({ _id: req.params.id, user: userId });
|
||||
if (!notification) {
|
||||
const notification = await Notification.findOne({ _id: paramsId(req), user: userId });
|
||||
if (notification === null) {
|
||||
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 { ApiError } from '../utils/ApiError.js';
|
||||
import { asyncHandler } from '../utils/asyncHandler.js';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
const uploadRouter = Router();
|
||||
|
||||
/**
|
||||
* Обёртка для multer: конвертирует multer errors в ApiError (400/413).
|
||||
*
|
||||
* @param fileFilter — имя поля файла (multer)
|
||||
* @returns middleware Express
|
||||
*/
|
||||
function multerHandler(fileFilter: 'file') {
|
||||
return (req: Request, res: Response, next: (err?: unknown) => void): void => {
|
||||
@@ -42,13 +47,13 @@ uploadRouter.post(
|
||||
requireAuth,
|
||||
multerHandler('file'),
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const authedReq = req as AuthenticatedRequest;
|
||||
if (!authedReq.user) {
|
||||
const userId = req.user?.id;
|
||||
if (userId === undefined) {
|
||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
||||
}
|
||||
|
||||
// Multer устанавливает req.file при успешной загрузке
|
||||
if (!req.file) {
|
||||
if (req.file === undefined) {
|
||||
throw new ApiError(400, 'NO_FILE', 'Файл не был загружен');
|
||||
}
|
||||
|
||||
|
||||
+38
-10
@@ -1,32 +1,51 @@
|
||||
import http from 'node:http';
|
||||
|
||||
import mongoose from 'mongoose';
|
||||
|
||||
import { createApp } from './app.js';
|
||||
import { connectDatabase } from './config/database.js';
|
||||
import { env } from './config/env.js';
|
||||
import { startPublicationScheduler, stopPublicationScheduler } from './services/publicationScheduler.service.js';
|
||||
import { createSocketServer } from './socket/socketServer.js';
|
||||
|
||||
/** Таймаут принудительного завершения, если соединения не закрылись. */
|
||||
const SHUTDOWN_TIMEOUT_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Завершает работу процесса после закрытия сервера.
|
||||
* Корректно завершает работу: scheduler → mongoose → HTTP-сервер.
|
||||
* Если незакрытые соединения не освобождаются за SHUTDOWN_TIMEOUT_MS —
|
||||
* процесс принудительно завершается с кодом 1.
|
||||
*
|
||||
* @param signal — сигнал, по которому остановлен процесс
|
||||
* @param server — HTTP-сервер для закрытия
|
||||
*/
|
||||
function shutdown(signal: string, server: http.Server): void {
|
||||
console.warn(`Сигнал ${signal} получен, завершение работы...`);
|
||||
|
||||
const forceExit = setTimeout(() => {
|
||||
console.error(`Не удалось завершить за ${String(SHUTDOWN_TIMEOUT_MS)} мс, принудительный выход`);
|
||||
process.exit(1);
|
||||
}, SHUTDOWN_TIMEOUT_MS);
|
||||
forceExit.unref();
|
||||
|
||||
stopPublicationScheduler();
|
||||
server.close(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
mongoose.connection.close()
|
||||
.catch((err: unknown) => {
|
||||
console.error('Ошибка при закрытии MongoDB:', err);
|
||||
})
|
||||
.finally(() => {
|
||||
server.close(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Точка входа приложения.
|
||||
*
|
||||
* Подключает MongoDB, создаёт HTTP-сервер, Socket.IO и Express, запускает scheduler.
|
||||
*
|
||||
* Socket.IO подключается к HTTP-серверу через engine.io (перехватывает /socket.io).
|
||||
* Express не отвечает на /socket.io (middleware в app.ts) — Socket.IO обрабатывает.
|
||||
*/
|
||||
async function main(): Promise<void> {
|
||||
await connectDatabase();
|
||||
@@ -37,13 +56,12 @@ async function main(): Promise<void> {
|
||||
// Socket.IO подключается к HTTP-серверу (engine.io перехватывает /socket.io)
|
||||
const io = createSocketServer(server);
|
||||
|
||||
// Express-приложение (с io для news routes)
|
||||
// Express НЕ отвечает на /socket.io — middleware в app.ts
|
||||
// Express-приложение (с io для news routes и scheduler)
|
||||
const app = createApp({ io });
|
||||
server.on('request', app);
|
||||
|
||||
// Запускаем планировщик отложенной публикации
|
||||
startPublicationScheduler(env.schedulerIntervalMs);
|
||||
// Запускаем планировщик отложенной публикации (с io для real-time уведомлений)
|
||||
startPublicationScheduler(env.schedulerIntervalMs, io);
|
||||
|
||||
server.listen(env.port, () => {
|
||||
console.warn(`News Editor API запущен на порту ${String(env.port)} (${env.nodeEnv})`);
|
||||
@@ -56,6 +74,16 @@ async function main(): Promise<void> {
|
||||
process.on('SIGTERM', () => {
|
||||
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) => {
|
||||
|
||||
@@ -5,9 +5,9 @@ import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/** Параметры для создания уведомления. */
|
||||
interface CreateNotificationParams {
|
||||
/** Пользователь-получатель. */
|
||||
/** Пользователь-получатель (ObjectId). */
|
||||
user: string;
|
||||
/** Пользователь-инициатор действия. */
|
||||
/** Пользователь-инициатор действия (ObjectId, может совпадать с user). */
|
||||
actor: string;
|
||||
/** Тип события. */
|
||||
type: NotificationType;
|
||||
@@ -23,18 +23,14 @@ interface CreateNotificationParams {
|
||||
* Сохраняет уведомление в БД и отправляет real-time событие через Socket.IO.
|
||||
*
|
||||
* @param io — экземпляр Socket.IO server
|
||||
* @param params — данные уведомления
|
||||
* @returns сохранённое уведомление (или null, если получатель = автор — не уведомляем себя)
|
||||
* @param params — данные уведомления (user/actor — ObjectId-строки,
|
||||
* Mongoose кастит их в ObjectId)
|
||||
*/
|
||||
export async function createNotification(
|
||||
io: SocketIOServer,
|
||||
params: CreateNotificationParams,
|
||||
): Promise<void> {
|
||||
// Не уведомляем пользователя о собственных действиях
|
||||
if (params.user === params.actor) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Mongoose кастит string → ObjectId (user/actor/newsId)
|
||||
const notification = await Notification.create({
|
||||
user: params.user,
|
||||
actor: params.actor,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import News from '../models/news.model.js';
|
||||
|
||||
import { createNotification } from './notification.service.js';
|
||||
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/**
|
||||
* Публикационный планировщик (MongoDB-backed poll).
|
||||
*
|
||||
@@ -10,18 +14,32 @@ import News from '../models/news.model.js';
|
||||
* Не использует setTimeout на конкретную статью — только poll.
|
||||
*/
|
||||
|
||||
/** Минимальное окно поиска недавно опубликованных (защита от часовых сдвигов). */
|
||||
const MIN_SCAN_WINDOW_MS = 60_000;
|
||||
const DEFAULT_INTERVAL_MS = 20_000;
|
||||
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
let ioRef: SocketIOServer | null = null;
|
||||
let currentIntervalMs = DEFAULT_INTERVAL_MS;
|
||||
|
||||
/**
|
||||
* Запускает периодический poll для автоматической публикации.
|
||||
*
|
||||
* @param intervalMs — интервал опроса в мс (по умолчанию 20000 = 20 сек)
|
||||
* @param io — Socket.IO server для real-time уведомлений (необязательно)
|
||||
* @returns void
|
||||
*/
|
||||
export function startPublicationScheduler(intervalMs = 20_000): void {
|
||||
export function startPublicationScheduler(
|
||||
intervalMs = DEFAULT_INTERVAL_MS,
|
||||
io?: SocketIOServer,
|
||||
): void {
|
||||
if (timer) {
|
||||
return;
|
||||
}
|
||||
if (io !== undefined) {
|
||||
ioRef = io;
|
||||
}
|
||||
currentIntervalMs = intervalMs;
|
||||
|
||||
const poll = async (): Promise<void> => {
|
||||
try {
|
||||
@@ -35,9 +53,10 @@ export function startPublicationScheduler(intervalMs = 20_000): void {
|
||||
|
||||
if (result.modifiedCount > 0) {
|
||||
console.log(`[scheduler] Опубликовано новостей: ${String(result.modifiedCount)}`);
|
||||
// Уведомляем авторов об автоматической публикации
|
||||
await notifyPublishedAuthors(now);
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
console.error('[scheduler] Ошибка при публикации:', err);
|
||||
}
|
||||
};
|
||||
@@ -56,6 +75,41 @@ export function startPublicationScheduler(intervalMs = 20_000): void {
|
||||
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).
|
||||
*/
|
||||
@@ -64,4 +118,5 @@ export function stopPublicationScheduler(): void {
|
||||
clearInterval(timer);
|
||||
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 type { SignOptions } from 'jsonwebtoken';
|
||||
|
||||
/**
|
||||
* Payload JWT-токена.
|
||||
*
|
||||
* @property id — ObjectId пользователя (обязателен по ТЗ)
|
||||
* @property sub — subject, дублирует id для совместимости
|
||||
*/
|
||||
export interface JwtPayload {
|
||||
readonly id: string;
|
||||
readonly sub: string;
|
||||
}
|
||||
import type { StringValue } from 'ms';
|
||||
|
||||
/**
|
||||
* Подписывает JWT-токен для пользователя с настройками из env.
|
||||
@@ -22,9 +11,13 @@ export interface JwtPayload {
|
||||
* @returns подписанный токен
|
||||
*/
|
||||
export function signUserToken(userId: string): string {
|
||||
const payload: Omit<JwtPayload, 'iat' | 'exp'> = { id: userId, sub: userId };
|
||||
const options: SignOptions = { expiresIn: 7 * 24 * 60 * 60 };
|
||||
const token = jwt.sign(payload, env.jwtSecret, options);
|
||||
// Payload по ТЗ: id обязателен, sub дублирует id для совместимости
|
||||
const payload = { id: userId, sub: userId };
|
||||
// Срок жизни берём из 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 : '';
|
||||
}
|
||||
|
||||
@@ -34,8 +27,8 @@ export function signUserToken(userId: string): string {
|
||||
* @param token — токен (без префикса Bearer)
|
||||
* @returns payload токена
|
||||
*/
|
||||
export function verifyUserToken(token: string): JwtPayload {
|
||||
const decoded = jwt.verify(token, env.jwtSecret);
|
||||
export function verifyUserToken(token: string): { id: string; sub: string } {
|
||||
const decoded = verify(token, env.jwtSecret);
|
||||
if (typeof decoded === 'string') {
|
||||
throw new Error('Неожиданный формат JWT payload');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user