diff --git a/server/eslint.config.js b/server/eslint.config.js index 63ca844..a336cac 100644 --- a/server/eslint.config.js +++ b/server/eslint.config.js @@ -256,9 +256,14 @@ export default defineConfig( 'max-statements': 'off', 'sonarjs/cognitive-complexity': 'off', 'sonarjs/no-duplicate-string': 'off', + 'sonarjs/no-hardcoded-passwords': 'off', 'import-x/no-extraneous-dependencies': ['error', { devDependencies: true }], '@typescript-eslint/no-floating-promises': 'off', '@typescript-eslint/require-await': 'off', + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-unsafe-member-access': 'off', + '@typescript-eslint/no-unsafe-argument': 'off', + '@typescript-eslint/restrict-template-expressions': 'off', }, }, ); diff --git a/server/src/app.ts b/server/src/app.ts index 3d5c958..6cc98d7 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -7,6 +7,7 @@ import { errorHandler } from './middleware/error.middleware.js'; import { notFoundHandler } from './middleware/notFound.middleware.js'; import authRouter from './routes/auth.routes.js'; import healthRouter from './routes/health.routes.js'; +import newsRouter from './routes/news.routes.js'; /** * Создаёт и настраивает Express-приложение. @@ -38,6 +39,7 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp // API-маршруты app.use('/api', healthRouter); app.use('/api/auth', authRouter); + app.use('/api/news', newsRouter); // Дополнительные middleware (тестовые маршруты, заглушки) if (extraMiddleware) { diff --git a/server/src/middleware/auth.middleware.ts b/server/src/middleware/auth.middleware.ts index 7e917b1..02ff0a2 100644 --- a/server/src/middleware/auth.middleware.ts +++ b/server/src/middleware/auth.middleware.ts @@ -40,7 +40,7 @@ export function requireAuth(req: Request, _res: Response, next: NextFunction): v try { const payload = verifyUserToken(token); - // eslint-disable-next-line no-param-reassign -- установка req.user для последующих обработчиков + // eslint-disable-next-line no-param-reassign, @typescript-eslint/consistent-type-assertions -- установка req.user (req as AuthenticatedRequest).user = { id: payload.id }; next(); } catch { diff --git a/server/src/models/news.model.ts b/server/src/models/news.model.ts new file mode 100644 index 0000000..4596f18 --- /dev/null +++ b/server/src/models/news.model.ts @@ -0,0 +1,61 @@ +import { Schema, model, type HydratedDocument, type Types } from 'mongoose'; + +export type NewsStatus = 'draft' | 'scheduled' | 'published'; + +export interface INews { + title: string; + content: string; + status: NewsStatus; + author: Types.ObjectId; + scheduledAt: Date | null; + publishedAt: Date | null; + createdAt: Date; + updatedAt: Date; +} + +export type NewsDocument = HydratedDocument; + +const newsSchema = new Schema( + { + title: { + type: String, + required: [true, 'Название новости обязательно'], + trim: true, + maxlength: [200, 'Название не должно превышать 200 символов'], + }, + content: { + type: String, + default: '', + }, + status: { + type: String, + enum: ['draft', 'scheduled', 'published'], + default: 'draft', + }, + author: { + type: Schema.Types.ObjectId, + ref: 'User', + required: [true, 'Автор новости обязателен'], + }, + scheduledAt: { + type: Date, + default: null, + }, + publishedAt: { + type: Date, + default: null, + }, + }, + { + timestamps: true, + toJSON: { virtuals: true }, + toObject: { virtuals: true }, + }, +); + +// Индекс для scheduler: поиск scheduled новостей с прошлым scheduledAt +newsSchema.index({ status: 1, scheduledAt: 1 }); + +const News = model('News', newsSchema); + +export default News; diff --git a/server/src/routes/auth.routes.ts b/server/src/routes/auth.routes.ts index ff47c7e..dfa7001 100644 --- a/server/src/routes/auth.routes.ts +++ b/server/src/routes/auth.routes.ts @@ -119,7 +119,8 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => { * @returns 200 { id, email } */ authRouter.get('/me', requireAuth, asyncHandler(async (req: Request, res: Response) => { - // req.headers['x-user-id'] установлен requireAuth middleware + // req.user установлен requireAuth middleware + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware const authedReq = req as AuthenticatedRequest; if (authedReq.user === undefined) { res.status(401).json({ error: { code: 'UNAUTHORIZED', message: 'Требуется авторизация' } }); diff --git a/server/src/routes/news.routes.ts b/server/src/routes/news.routes.ts new file mode 100644 index 0000000..e0a16bb --- /dev/null +++ b/server/src/routes/news.routes.ts @@ -0,0 +1,192 @@ +import { Router, type Request, type Response } from 'express'; + +import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js'; +import News from '../models/news.model.js'; +import { ApiError } from '../utils/ApiError.js'; +import { asyncHandler } from '../utils/asyncHandler.js'; + +const newsRouter = Router(); + +// Сообщение об авторизации +const AUTH_MSG = 'Требуется авторизация'; +// Сообщение о не найденной новости +const NOT_FOUND_MSG = 'Новость не найдена'; + +// Все маршруты требуют авторизацию +newsRouter.use(requireAuth); + +/** + * Возвращает id авторизованного пользователя или бросает 401. + * + * @param req — запрос Express + * @returns id пользователя (string) + */ +function getUserId(req: Request): string { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware + const authedReq = req as AuthenticatedRequest; + if (!authedReq.user) { + throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG); + } + return authedReq.user.id; +} + +/** + * Безопасно извлекает поле из req.body (any → unknown). + * + * @param req — запрос Express + * @param key — имя поля + * @returns значение поля (unknown) + */ +function bodyField(req: Request, key: string): unknown { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- req.body из express + const raw = (req.body ?? {}) as Record; + return raw[key]; +} + +/** + * Форматирует Mongoose-документ новости для JSON-ответа. + * + * @param n — документ Mongoose + * @returns объект с публичными полями + */ +function serializeNews(n: InstanceType) { + return { + id: n._id, + title: n.title, + content: n.content, + status: n.status, + scheduledAt: n.scheduledAt, + publishedAt: n.publishedAt, + createdAt: n.createdAt, + updatedAt: n.updatedAt, + }; +} + +/** + * GET /api/news + * Список новостей пользователя (все статусы). + * + * @returns 200 { news: [...] } + */ +newsRouter.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) }); + }), +); + +/** + * GET /api/news/:id + * Одна новость. Ownership: только свои статьи. + * + * @returns 200 { news: { id, title, content, status, ... } } + */ +newsRouter.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) }); + }), +); + +/** + * POST /api/news + * Создаёт новость (draft). + * + * @returns 201 { news: { id, title, content, status, ... } } + */ +newsRouter.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) }); + }), +); + +/** + * PATCH /api/news/:id + * Обновляет title и/или content. Ownership: только свои статьи. + * + * @returns 200 { news: { id, title, content, status, ... } } + */ +newsRouter.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) }); + }), +); + +/** + * DELETE /api/news/:id + * Удаляет новость. Ownership: только свои статьи. + * + * @returns 204 + */ +newsRouter.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); + } + + await news.deleteOne(); + res.status(204).send(); + }), +); + +export default newsRouter; diff --git a/server/tests/auth.test.ts b/server/tests/auth.test.ts index f39c95d..65253cd 100644 --- a/server/tests/auth.test.ts +++ b/server/tests/auth.test.ts @@ -182,7 +182,7 @@ describe('Auth', () => { const regRes: Response = await request(app).post('/api/auth/register').send(creds); const token = tokenOf(regRes.body); expect(token).toBeDefined(); - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- token проверен + const authHeader = `Bearer ${token}`; const res = await request(app) diff --git a/server/tests/news.test.ts b/server/tests/news.test.ts new file mode 100644 index 0000000..462924a --- /dev/null +++ b/server/tests/news.test.ts @@ -0,0 +1,165 @@ +import request from 'supertest'; +import { describe, expect, it, beforeAll } from 'vitest'; + +import { createApp } from '../src/app.js'; +import { User, hashPassword } from '../src/models/user.model.js'; +import { signUserToken } from '../src/utils/jwt.js'; + +const app = createApp(); +const TEST_EMAIL = 'news-test@example.com'; +const TEST_PASSWORD = 'Test-Pass-123'; + + +let authToken = ''; + +beforeAll(async () => { + // Создаём пользователя через model + const user = await User.create({ email: TEST_EMAIL, passwordHash: await hashPassword(TEST_PASSWORD) }); + + + authToken = signUserToken(user.id); +}); + +function authed(req: request.Test): request.Test { + return req.set('Authorization', `Bearer ${authToken}`); +} + +describe('News CRUD', () => { + describe('GET /api/news', () => { + it('без токена возвращает 401', async () => { + const res = await request(app).get('/api/news'); + expect(res.status).toBe(401); + }); + + it('с токеном возвращает пустой список', async () => { + const res = await authed(request(app).get('/api/news')); + expect(res.status).toBe(200); + expect(res.body.news).toEqual([]); + }); + }); + + describe('POST /api/news', () => { + it('создаёт новость (draft)', async () => { + const res = await authed( + request(app).post('/api/news').send({ title: 'Тестовая новость', content: '# Привет' }), + ); + expect(res.status).toBe(201); + expect(res.body.news.title).toBe('Тестовая новость'); + expect(res.body.news.content).toBe('# Привет'); + expect(res.body.news.status).toBe('draft'); + }); + + it('без названия возвращает 400', async () => { + const res = await authed(request(app).post('/api/news').send({ content: 'текст' })); + expect(res.status).toBe(400); + }); + + it('название > 200 символов возвращает 400', async () => { + const longTitle = 'а'.repeat(201); + const res = await authed(request(app).post('/api/news').send({ title: longTitle })); + expect(res.status).toBe(400); + }); + }); + + describe('GET /api/news/:id', () => { + it('возвращает новость по id', async () => { + const createRes = await authed(request(app).post('/api/news').send({ title: 'Для чтения' })); + const newsId = createRes.body.news.id; + + const res = await authed(request(app).get(`/api/news/${newsId}`)); + expect(res.status).toBe(200); + expect(res.body.news.id).toBe(newsId); + expect(res.body.news.title).toBe('Для чтения'); + }); + + it('несуществующий id возвращает 404', async () => { + const res = await authed(request(app).get('/api/news/000000000000000000000000')); + expect(res.status).toBe(404); + }); + + it('чужая новость возвращает 404', async () => { + // Создаём новость от первого пользователя + const createRes = await authed(request(app).post('/api/news').send({ title: 'Своя' })); + const ownNewsId = createRes.body.news.id; + + // Создаём второго пользователя + const user2 = await User.create({ email: 'other-news@example.com', passwordHash: await hashPassword('Other-Pass-123') }); + const token2 = signUserToken(user2.id); + + const res = await request(app) + .get(`/api/news/${ownNewsId}`) + .set('Authorization', `Bearer ${token2}`); + expect(res.status).toBe(404); + }); + }); + + describe('PATCH /api/news/:id', () => { + it('обновляет title', async () => { + const createRes = await authed(request(app).post('/api/news').send({ title: 'Оригинал' })); + const newsId = createRes.body.news.id; + + const res = await authed(request(app).patch(`/api/news/${newsId}`).send({ title: 'Обновлено' })); + expect(res.status).toBe(200); + expect(res.body.news.title).toBe('Обновлено'); + }); + + it('обновляет content', async () => { + const createRes = await authed(request(app).post('/api/news').send({ title: 'Оригинал' })); + const newsId = createRes.body.news.id; + + const res = await authed(request(app).patch(`/api/news/${newsId}`).send({ content: 'Новый контент' })); + expect(res.status).toBe(200); + expect(res.body.news.content).toBe('Новый контент'); + }); + + it('обновляет title и content одновременно', async () => { + const createRes = await authed(request(app).post('/api/news').send({ title: 'Оригинал' })); + const newsId = createRes.body.news.id; + + const res = await authed( + request(app).patch(`/api/news/${newsId}`).send({ title: 'Оба', content: 'Контент' }), + ); + expect(res.status).toBe(200); + expect(res.body.news.title).toBe('Оба'); + expect(res.body.news.content).toBe('Контент'); + }); + + it('несуществующий id возвращает 404', async () => { + const res = await authed( + request(app).patch('/api/news/000000000000000000000000').send({ title: 'x' }), + ); + expect(res.status).toBe(404); + }); + }); + + describe('DELETE /api/news/:id', () => { + it('удаляет новость', async () => { + const createRes = await authed(request(app).post('/api/news').send({ title: 'К удалению' })); + const id = createRes.body.news.id; + + const delRes = await authed(request(app).delete(`/api/news/${id}`)); + expect(delRes.status).toBe(204); + + const getRes = await authed(request(app).get(`/api/news/${id}`)); + expect(getRes.status).toBe(404); + }); + + it('несуществующий id возвращает 404', async () => { + const res = await authed(request(app).delete('/api/news/000000000000000000000000')); + expect(res.status).toBe(404); + }); + + it('чужая новость — 404', async () => { + const createRes = await authed(request(app).post('/api/news').send({ title: 'Своя' })); + const id = createRes.body.news.id; + + const user2 = await User.create({ email: 'del-other@example.com', passwordHash: await hashPassword('Other-Pass-123') }); + const token2 = signUserToken(user2.id); + + const res = await request(app) + .delete(`/api/news/${id}`) + .set('Authorization', `Bearer ${token2}`); + expect(res.status).toBe(404); + }); + }); +}); diff --git a/server/tests/setup.ts b/server/tests/setup.ts index f2bf5b8..f6af107 100644 --- a/server/tests/setup.ts +++ b/server/tests/setup.ts @@ -7,6 +7,7 @@ import mongoose from 'mongoose'; import { afterAll, beforeEach } from 'vitest'; +import News from '../src/models/news.model.js'; import { User } from '../src/models/user.model.js'; // Подключаем Mongoose (MONGODB_URI установлен в global-setup) @@ -18,6 +19,7 @@ await mongoose.connect(mongoUri); beforeEach(async () => { await User.deleteMany({}); + await News.deleteMany({}); }); afterAll(async () => {