Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29b0a16f94 | ||
|
|
dad4642197 | ||
|
|
65c44f570c | ||
|
|
476250d5e3 | ||
|
|
34fa29c0fc | ||
|
|
d4f984e911 | ||
|
|
ac85d71c65 | ||
|
|
281daa4717 | ||
|
|
62c82da7af | ||
|
|
7c89a93442 |
@@ -0,0 +1,9 @@
|
||||
node_modules
|
||||
client/node_modules
|
||||
server/node_modules
|
||||
server/dist
|
||||
client/dist
|
||||
server/uploads
|
||||
.git
|
||||
*.log
|
||||
.env
|
||||
@@ -0,0 +1,3 @@
|
||||
JWT_SECRET=change-me-in-production
|
||||
PORT=8080
|
||||
CLIENT_ORIGIN=http://localhost:8080
|
||||
@@ -1,54 +1,88 @@
|
||||
# News Editor
|
||||
|
||||
Full-stack application for creating, editing, and publishing news articles with real-time notifications.
|
||||
Full-stack приложение для создания, редактирования и публикации новостей. Markdown-редактор, real-time уведомления, отложенная публикация.
|
||||
|
||||
## Architecture
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
┌──────────────────────────┐
|
||||
│ React Client │
|
||||
│ Login/Register, News list,
|
||||
│ Markdown editor, Preview,
|
||||
│ Notifications bell
|
||||
└─────────────┬────────────┘
|
||||
│ REST + JWT / Socket.IO
|
||||
▼
|
||||
┌──────────────────────────┐
|
||||
│ Express Backend │
|
||||
│ Auth middleware, News CRUD,
|
||||
│ Upload, Scheduler,
|
||||
│ Socket.IO notifications
|
||||
└─────────────┬────────────┘
|
||||
┌──────────────────────────────────────────┐
|
||||
│ Nginx (client) │
|
||||
│ React SPA + reverse proxy │
|
||||
│ /api → server, /socket.io → ws, │
|
||||
│ /uploads → server │
|
||||
└────────────────────┬─────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────┐
|
||||
│ MongoDB Atlas │
|
||||
│ users, news,
|
||||
│ notifications
|
||||
└──────────────────────────┘
|
||||
┌──────────────────────────────────────────┐
|
||||
│ Express Backend │
|
||||
│ Auth (JWT), News CRUD, Upload (multer), │
|
||||
│ Scheduler, Socket.IO, Notifications │
|
||||
└────────────────────┬─────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────────────┐
|
||||
│ MongoDB │
|
||||
│ users, news, notifications │
|
||||
└──────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Tech Stack
|
||||
## Стек технологий
|
||||
|
||||
| Layer | Technology |
|
||||
|----------|-----------------------------------------|
|
||||
| Backend | Node.js, Express, MongoDB/Mongoose |
|
||||
| Auth | JWT (jsonwebtoken), bcrypt |
|
||||
| Real-time| Socket.IO |
|
||||
| Upload | multer (local storage + express.static) |
|
||||
| Frontend | React 18, Vite, function components |
|
||||
| Editor | Markdown (react-markdown, remark-gfm) |
|
||||
| Tests | Vitest, Supertest, mongodb-memory-server|
|
||||
| Слой | Технология |
|
||||
|-------------|-----------------------------------------------------|
|
||||
| Бэкенд | Node.js 22, Express, TypeScript (strict) |
|
||||
| Авторизация | JWT (jsonwebtoken), bcrypt (cost 12) |
|
||||
| Real-time | Socket.IO (JWT auth, user rooms) |
|
||||
| Файлы | multer (disk storage, UUID filenames, MIME whitelist) |
|
||||
| Фронтенд | React 18, TypeScript, Vite, react-router-dom |
|
||||
| Стили | SCSS Modules (per-component) + global base |
|
||||
| Редактор | Markdown (react-markdown, remark-gfm, rehype-sanitize) |
|
||||
| Тесты | Vitest, Supertest, mongodb-memory-server |
|
||||
| Деплой | Docker Compose (nginx + node + mongo) |
|
||||
|
||||
## Prerequisites
|
||||
## Структура проекта
|
||||
|
||||
- Node.js >= 18
|
||||
- MongoDB Atlas cluster (or local MongoDB)
|
||||
- npm
|
||||
```
|
||||
news-editor/
|
||||
├── package.json ← root scripts (dev, test, lint, build)
|
||||
├── docker-compose.yml ← production-стек
|
||||
├── .env ← env для docker (JWT_SECRET, PORT)
|
||||
├── server/
|
||||
│ ├── Dockerfile ← multi-stage: tsc → node:22-alpine
|
||||
│ ├── src/
|
||||
│ │ ├── app.ts ← фабрика Express-приложения
|
||||
│ │ ├── server.ts ← точка входа (HTTP + Socket.IO + scheduler)
|
||||
│ │ ├── config/ ← env, database
|
||||
│ │ ├── middleware/ ← auth (JWT), error, notFound, upload (multer)
|
||||
│ │ ├── models/ ← User, News, Notification (Mongoose)
|
||||
│ │ ├── routes/ ← auth, news, notification, upload, health
|
||||
│ │ ├── services/ ← publicationScheduler, notification
|
||||
│ │ ├── socket/ ← Socket.IO server + типизация
|
||||
│ │ └── utils/ ← ApiError, asyncHandler, jwt
|
||||
│ └── tests/ ← интеграционные тесты (Vitest + Supertest)
|
||||
└── client/
|
||||
├── Dockerfile ← multi-stage: vite build → nginx:alpine
|
||||
├── nginx.conf ← SPA + proxy
|
||||
└── src/
|
||||
├── api/ ← fetch клиент (apiFetch, apiUpload), типы
|
||||
├── auth/ ← AuthContext (login, register, logout)
|
||||
├── components/ ← ProtectedRoute, NotificationBell, MarkdownToolbar
|
||||
├── hooks/ ← useNewsEditor, useNotifications, useSocket
|
||||
├── pages/ ← Login, Register, Home, NewsList, NewsEditor
|
||||
├── styles/ ← global.scss (base reset + shared)
|
||||
└── App.tsx ← BrowserRouter + Routes
|
||||
```
|
||||
|
||||
## Setup
|
||||
## Требования
|
||||
|
||||
### 1. Install dependencies
|
||||
- Node.js >= 20
|
||||
- npm >= 10
|
||||
- MongoDB (локальная, Atlas, или Docker)
|
||||
- Docker + Docker Compose (для production-деплоя)
|
||||
|
||||
## Разработка
|
||||
|
||||
### 1. Установка зависимостей
|
||||
|
||||
```bash
|
||||
npm install
|
||||
@@ -56,132 +90,259 @@ npm --prefix server install
|
||||
npm --prefix client install
|
||||
```
|
||||
|
||||
### 2. Configure environment
|
||||
### 2. Конфигурация окружения
|
||||
|
||||
```bash
|
||||
cp server/.env.example server/.env
|
||||
cp client/.env.example client/.env
|
||||
```
|
||||
|
||||
Edit `server/.env`:
|
||||
Редактируем `server/.env`:
|
||||
|
||||
```env
|
||||
MONGODB_URI=mongodb+srv://<user>:<pass>@<cluster>.example.net/newsEditor
|
||||
JWT_SECRET=<generate-a-long-random-string>
|
||||
CLIENT_ORIGIN=http://localhost:5173
|
||||
NODE_ENV=development
|
||||
PORT=3000
|
||||
MONGODB_URI=mongodb://localhost:27017/news-editor
|
||||
JWT_SECRET=dev-secret-change-in-production
|
||||
JWT_EXPIRES_IN=7d
|
||||
CLIENT_ORIGIN=http://localhost:5173,http://192.168.50.7:5173
|
||||
MAX_UPLOAD_SIZE=20971520
|
||||
SCHEDULER_INTERVAL_MS=20000
|
||||
```
|
||||
|
||||
Edit `client/.env`:
|
||||
|
||||
```env
|
||||
VITE_API_URL=http://localhost:3000
|
||||
```
|
||||
|
||||
### 3. Run
|
||||
### 3. Запуск MongoDB (если не запущена)
|
||||
|
||||
```bash
|
||||
# Both server + client (uses concurrently)
|
||||
# Вариант A: Docker
|
||||
docker run -d --name mongo -p 27017:27017 mongo:7
|
||||
|
||||
# Вариант B: Локальная установка
|
||||
mongod --dbpath ~/mongodb-data
|
||||
```
|
||||
|
||||
### 4. Запуск
|
||||
|
||||
```bash
|
||||
# Сервер + клиент одновременно (concurrently)
|
||||
npm run dev
|
||||
|
||||
# Or separately
|
||||
npm --prefix server run dev
|
||||
npm --prefix client run dev
|
||||
# Или по отдельности
|
||||
npm --prefix server run dev # http://localhost:3000
|
||||
npm --prefix client run dev # http://localhost:5173
|
||||
```
|
||||
|
||||
- Backend: http://localhost:3000
|
||||
- Frontend: http://localhost:5173
|
||||
- Health check: http://localhost:3000/api/health
|
||||
- Бэкенд: http://localhost:3000
|
||||
- Фронтенд: http://localhost:5173
|
||||
- LAN: http://192.168.50.7:5173
|
||||
- Health: http://localhost:3000/api/health
|
||||
|
||||
## API Endpoints
|
||||
## Production (Docker Compose)
|
||||
|
||||
### Auth
|
||||
Полный production-стек одной командой `docker compose up`.
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|----------------------|------|--------------------------------|
|
||||
| POST | `/api/auth/register` | – | Register, returns `{user, token}` |
|
||||
| POST | `/api/auth/login` | – | Login, returns `{user, token}` |
|
||||
### Архитектура
|
||||
|
||||
### News (authenticated)
|
||||
| Сервис | Образ | Описание |
|
||||
|----------|--------------------------------|-----------------------------------|
|
||||
| `mongo` | mongo:7 | MongoDB с healthcheck |
|
||||
| `server` | multi-stage (node:22-alpine) | Express API + Socket.IO |
|
||||
| `client` | multi-stage (nginx:alpine) | React SPA + reverse proxy |
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|------------------------|------------------------------------|
|
||||
| GET | `/api/news` | List own news (`?status=&page=&limit=`) |
|
||||
| GET | `/api/news/:id` | Get one news article |
|
||||
| POST | `/api/news` | Create draft |
|
||||
| PATCH | `/api/news/:id` | Update own article |
|
||||
| DELETE | `/api/news/:id` | Delete own article |
|
||||
| POST | `/api/news/:id/publish`| Publish immediately |
|
||||
| POST | `/api/news/:id/schedule`| Schedule publication (`{publishAt}`) |
|
||||
### Запуск
|
||||
|
||||
### Public
|
||||
```bash
|
||||
# 1. Настроить .env (JWT_SECRET обязателен)
|
||||
cp .env.docker .env
|
||||
# Отредактируйте JWT_SECRET
|
||||
|
||||
| Method | Path | Description |
|
||||
|--------|-----------------------|--------------------------------------|
|
||||
| GET | `/api/public/news` | List published articles |
|
||||
| GET | `/api/public/news/:id`| Get one published article |
|
||||
# 2. Собрать и запустить
|
||||
docker compose up -d --build
|
||||
|
||||
### Upload
|
||||
# 3. Проверить
|
||||
curl http://localhost:8080/api/health
|
||||
# → {"status":"ok"}
|
||||
```
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|---------------|------|------------------------------------------|
|
||||
| POST | `/api/uploads`| ✓ | Upload file (multipart), returns `{file}` |
|
||||
Приложение доступно на `http://localhost:8080` (или `http://<IP>:8080` для LAN).
|
||||
|
||||
### Notifications
|
||||
### Переменные окружения (.env)
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|---------------------------------|------|--------------------------|
|
||||
| GET | `/api/notifications` | ✓ | List notifications |
|
||||
| PATCH | `/api/notifications/:id/read` | ✓ | Mark as read |
|
||||
| POST | `/api/notifications/read-all` | ✓ | Mark all as read |
|
||||
| Переменная | По умолчанию | Описание |
|
||||
|-----------------|----------------------|---------------------------------------------|
|
||||
| `JWT_SECRET` | — (обязательна) | Секрет подписи JWT |
|
||||
| `PORT` | `8080` | Внешний порт nginx |
|
||||
| `CLIENT_ORIGIN` | `http://localhost:8080` | CORS origin (через запятую — несколько) |
|
||||
|
||||
## Scheduled Publication
|
||||
### Остановка
|
||||
|
||||
The backend runs a poller every 15 seconds that finds articles with:
|
||||
```bash
|
||||
# Остановить контейнеры
|
||||
docker compose down
|
||||
|
||||
# Остановить + удалить данные (MongoDB + uploads)
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
### Файлы
|
||||
|
||||
| Файл | Назначение |
|
||||
|-----------------------|-----------------------------------------------|
|
||||
| `docker-compose.yml` | Оркестрация: mongo + server + client |
|
||||
| `server/Dockerfile` | Multi-stage: tsc build → node:22-alpine |
|
||||
| `client/Dockerfile` | Multi-stage: vite build → nginx:alpine |
|
||||
| `client/nginx.conf` | SPA fallback + proxy /api, /uploads, /socket.io |
|
||||
| `.dockerignore` | Исключения из build context |
|
||||
|
||||
## API
|
||||
|
||||
### Авторизация
|
||||
|
||||
| Method | Path | Auth | Описание |
|
||||
|--------|----------------------|------|---------------------------------------|
|
||||
| POST | `/api/auth/register` | – | Регистрация, возвращает `{token, user}` |
|
||||
| POST | `/api/auth/login` | – | Логин, возвращает `{token, user}` |
|
||||
| GET | `/api/auth/me` | ✓ | Текущий пользователь |
|
||||
|
||||
### Новости (авторизовано)
|
||||
|
||||
| Method | Path | Описание |
|
||||
|--------|-------------------------|---------------------------------------|
|
||||
| GET | `/api/news` | Список своих новостей |
|
||||
| GET | `/api/news/:id` | Одна новость |
|
||||
| POST | `/api/news` | Создать черновик |
|
||||
| PATCH | `/api/news/:id` | Обновить свою новость |
|
||||
| DELETE扭头 | `/api/news/:id` | Удалить свою новость |
|
||||
| POST | `/api/news/:id/publish` | Опубликовать немедленно |
|
||||
| POST | `/api/news/:id/schedule`| Отложенная публикация (`{scheduledAt}`) |
|
||||
|
||||
### Уведомления (авторизовано)
|
||||
|
||||
| Method | Path | Описание |
|
||||
|--------|-----------------------------------|-----------------------------|
|
||||
| GET | `/api/notifications` | Список (последние 50) |
|
||||
| GET | `/api/notifications/unread-count` | Счётчик непрочитанных |
|
||||
| PATCH | `/api/notifications/:id/read` | Прочитать одно |
|
||||
| POST | `/api/notifications/read-all` | Прочитать все |
|
||||
|
||||
### Загрузка файлов
|
||||
|
||||
| Method | Path | Auth | Описание |
|
||||
|--------|----------------------|------|-------------------------------------------|
|
||||
| POST | `/api/uploads` | ✓ | Загрузить файл (multipart) |
|
||||
| GET | `/uploads/:filename` | – | Статическая раздача загруженного файла |
|
||||
|
||||
**MIME whitelist**: image/jpeg, image/png, image/gif, image/webp, application/pdf, application/msword, .docx
|
||||
|
||||
### Health
|
||||
|
||||
| Method | Path | Описание |
|
||||
|--------|---------------|-------------------|
|
||||
| GET | `/api/health` | `{"status":"ok"}` |
|
||||
|
||||
## Real-time уведомления (Socket.IO)
|
||||
|
||||
Socket.IO подключён к тому же HTTP-серверу, что и Express.
|
||||
|
||||
### Подключение клиента
|
||||
|
||||
```js
|
||||
{ status: "scheduled", publishAt: { $lte: now } }
|
||||
import { io } from 'socket.io-client';
|
||||
|
||||
const socket = io('http://localhost:8080', {
|
||||
auth: { token: jwtToken },
|
||||
transports: ['websocket', 'polling'],
|
||||
});
|
||||
|
||||
// Real-time уведомления
|
||||
socket.on('notification', (data) => {
|
||||
console.log(data.title, data.message);
|
||||
});
|
||||
```
|
||||
|
||||
and atomically transitions them to `published`. This survives process restarts — no in-memory `setTimeout` per article.
|
||||
### Аутентификация
|
||||
|
||||
## Real-time Notifications
|
||||
JWT передаётся через `handshake.auth.token`. Сервер верифицирует токен в `io.use()` middleware и при неудаче отклоняет подключение.
|
||||
|
||||
Socket.IO runs on the same HTTP server as Express. The client authenticates with the same JWT via `io(API_URL, { auth: { token } })`.
|
||||
### События
|
||||
|
||||
Events: `news.created`, `news.updated`, `news.deleted`, `news.scheduled`, `news.published`.
|
||||
| Event | Payload | Когда |
|
||||
|----------------|--------------------------------------------------|--------------------------------|
|
||||
| `notification` | `{id, type, title, message, isRead, createdAt}` | news.deleted, published, scheduled |
|
||||
|
||||
Notifications are persisted to MongoDB so the bell survives page reloads.
|
||||
### Rooms
|
||||
|
||||
## Testing
|
||||
Каждый подключённый socket добавляется в room `user:{userId}`. Уведомления отправляются через `io.to('user:{id}').emit(...)`.
|
||||
|
||||
## Отложенная публикация
|
||||
|
||||
Бэкенд запускает poller каждые 20 секунд (настраивается через `SCHEDULER_INTERVAL_MS`), который находит статьи:
|
||||
|
||||
```js
|
||||
{ status: 'scheduled', scheduledAt: { $lte: now } }
|
||||
```
|
||||
|
||||
и атомарно переводит их в `published` через `findOneAndUpdate`. Выживает после перезапуска процесса — без in-memory `setTimeout` на статью.
|
||||
|
||||
## Загрузка файлов
|
||||
|
||||
Файлы хранятся на файловой системе (`UPLOAD_DIR`, по умолчанию `server/uploads/`). Имена файлов — UUID (защита от коллизий). Максимальный размер: 20 МБ (настраивается через `MAX_UPLOAD_SIZE`).
|
||||
|
||||
## Фронтенд: Markdown-редактор
|
||||
|
||||
- **Toolbar**: Bold, Italic, Heading, Quote, Code, Link, Image, File
|
||||
- **Preview**: react-markdown + remark-gfm + rehype-sanitize
|
||||
- **Upload**: изображение/файл → вставка markdown-ссылки в textarea
|
||||
- **UI зависит от статуса**:
|
||||
- Draft/scheduled: Сохранить + Опубликовать + Удалить + Schedule + toggle Редактор/Предпросмотр
|
||||
- Published: Сохранить + Удалить (по умолчанию preview, нет publish/schedule)
|
||||
|
||||
## Фронтенд: Колокольчик уведомлений
|
||||
|
||||
- 🔔 иконка с badge (счётчик непрочитанных)
|
||||
- Клик → панель со списком уведомлений
|
||||
- Клик по уведомлению → пометить прочитанным
|
||||
- "Прочитать все" → пометить все
|
||||
- Real-time: новые уведомления появляются без перезагрузки (Socket.IO)
|
||||
|
||||
## Формат ошибок
|
||||
|
||||
Все ошибки имеют единый формат:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "VALIDATION_ERROR",
|
||||
"message": "Пароль должен содержать минимум 8 символов"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Тесты
|
||||
|
||||
```bash
|
||||
npm --prefix server test # Vitest + Supertest + mongodb-memory-server
|
||||
npm test # all tests
|
||||
npm --prefix server test # Vitest + Supertest + mongodb-memory-server (46 тестов)
|
||||
npm test # все тесты
|
||||
```
|
||||
|
||||
## Lint
|
||||
## Линт
|
||||
|
||||
```bash
|
||||
npm run lint # ESLint for server + client
|
||||
npm run lint # ESLint (strictTypeChecked + sonarjs) для server + client
|
||||
```
|
||||
|
||||
## Production Build
|
||||
## Production-сборка
|
||||
|
||||
```bash
|
||||
npm --prefix client run build
|
||||
# Output: client/dist/ (static files, deployable to any static host)
|
||||
# Результат: client/dist/ (статические файлы, можно деплоить на любой хостинг)
|
||||
```
|
||||
|
||||
Backend should be deployed to a long-running Node host (not serverless) because of Socket.IO connections and the scheduler.
|
||||
## Демонстрационный сценарий
|
||||
|
||||
## Demo Flow
|
||||
|
||||
1. Register → Login → see JWT with user `id`
|
||||
2. Create a draft → add markdown (heading, bold, quote, code block)
|
||||
3. Upload an image → insert into article
|
||||
4. Upload a PDF → insert link
|
||||
5. Open Preview → see rendered markdown
|
||||
6. Save draft → see notification in bell
|
||||
7. Schedule publication for 1–2 min ahead → watch it auto-publish
|
||||
8. Create another article → publish immediately → delete it
|
||||
9. Bell shows all events in real-time
|
||||
1. Регистрация → Логин → JWT с `id` пользователя
|
||||
2. Создать черновик → добавить markdown через toolbar
|
||||
3. Загрузить изображение → получить URL → вставить в статью
|
||||
4. Сохранить черновик → виден в списке (с preview контента)
|
||||
5. Запланировать публикацию на 1–2 мин вперёд → наблюдать авто-публикацию
|
||||
6. Опубликовать немедленно → статья live (UI переключается в read-only preview)
|
||||
7. Колокольчик показывает real-time события
|
||||
8. Удалить статью
|
||||
|
||||
+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=
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY client/package*.json ./
|
||||
RUN npm ci
|
||||
COPY client/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY client/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
+52
-7
@@ -18,6 +18,8 @@ const CONFIG_ROOT = import.meta.dirname;
|
||||
const TEST_FILES = ['**/*.{test,spec}.{ts,tsx}'];
|
||||
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/vite.config.*'];
|
||||
|
||||
/* eslint-disable no-unused-vars -- eslint.config.js lintится самим собой */
|
||||
|
||||
/* Забираем правила из пресетов плагинов */
|
||||
const reactRecommendedRules =
|
||||
react.configs.flat?.recommended?.rules ??
|
||||
@@ -50,8 +52,11 @@ export default defineConfig(
|
||||
{
|
||||
name: 'client/linter-policy',
|
||||
linterOptions: {
|
||||
noInlineConfig: false,
|
||||
// Inline-директивы (eslint-disable и т.п.) в коде запрещены.
|
||||
// Единственный способ отключить правило — file-level override в этом конфиге.
|
||||
noInlineConfig: true,
|
||||
reportUnusedDisableDirectives: 'error',
|
||||
reportUnusedInlineConfigs: 'error',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -95,6 +100,8 @@ export default defineConfig(
|
||||
'react/no-unstable-nested-components': ['error', { allowAsProps: false }],
|
||||
/* В TS prop-types не нужны */
|
||||
'react/prop-types': 'off',
|
||||
/* React 18 с jsx: react-jsx не требует React в scope */
|
||||
'react/react-in-jsx-scope': 'off',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -272,12 +279,6 @@ export default defineConfig(
|
||||
'newlines-between': 'always',
|
||||
}],
|
||||
|
||||
/* Запрет необъяснённых disable-директив */
|
||||
'@eslint-community/eslint-comments/disable-enable-pair': ['error', { allowWholeFile: false }],
|
||||
'@eslint-community/eslint-comments/no-aggregating-enable': 'error',
|
||||
'@eslint-community/eslint-comments/no-duplicate-disable': 'error',
|
||||
'@eslint-community/eslint-comments/no-unlimited-disable': 'error',
|
||||
'@eslint-community/eslint-comments/require-description': ['error', { ignore: ['eslint-enable'] }],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -308,4 +309,48 @@ export default defineConfig(
|
||||
'@typescript-eslint/require-await': 'off',
|
||||
},
|
||||
},
|
||||
|
||||
/* ── Файловые исключения (единственный способ отключить правило) ── */
|
||||
{
|
||||
name: 'client/api-client',
|
||||
files: ['src/api/client.ts'],
|
||||
rules: {
|
||||
// fetch.json() возвращает any — assertion неизбежен
|
||||
'@typescript-eslint/no-unsafe-type-assertion': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'client/news-editor',
|
||||
files: ['src/hooks/useNewsEditor.ts'],
|
||||
rules: {
|
||||
// Хук-оркестратор: 4 action-обработчика + toolbar + upload
|
||||
'max-lines-per-function': 'off',
|
||||
// window.confirm для подтверждения удаления
|
||||
'no-alert': 'off',
|
||||
// e.target.value = '' — сброс file input (стандартный паттерн)
|
||||
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['e'] }],
|
||||
// async IIFE в useEffect для загрузки новости
|
||||
'@typescript-eslint/no-floating-promises': 'off',
|
||||
// newsId гарантированно string (проверено isNew)
|
||||
'@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',
|
||||
files: ['src/pages/LoginPage.tsx', 'src/pages/RegisterPage.tsx'],
|
||||
rules: {
|
||||
// .then/.catch/.finally цепочка в handleSubmit: rejection обработан,
|
||||
// но no-floating-promises не распознаёт pattern (см. комментарий в файле)
|
||||
'@typescript-eslint/no-floating-promises': 'off',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# SPA fallback
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# Proxy /api → server
|
||||
location /api/ {
|
||||
proxy_pass http://server:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
# Proxy /uploads → server
|
||||
location /uploads/ {
|
||||
proxy_pass http://server:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
}
|
||||
|
||||
# Proxy /socket.io → server (WebSocket)
|
||||
location /socket.io/ {
|
||||
proxy_pass http://server:3000;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
}
|
||||
Generated
+1
-4
@@ -14,7 +14,7 @@
|
||||
"react-router-dom": "^7.2.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-gfm": "^4.0.0",
|
||||
"socket.io-client": "^4.8.1"
|
||||
"socket.io-client": "^4.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
|
||||
@@ -1986,14 +1986,12 @@
|
||||
"version": "15.7.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
|
||||
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "18.3.31",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
|
||||
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
@@ -3293,7 +3291,6 @@
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/damerau-levenshtein": {
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
"react-router-dom": "^7.2.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-gfm": "^4.0.0",
|
||||
"socket.io-client": "^4.8.1"
|
||||
"socket.io-client": "^4.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
|
||||
|
||||
import { AuthProvider } from './auth/AuthContext.js';
|
||||
import { ProtectedRoute } from './components/ProtectedRoute.js';
|
||||
import { HomePage } from './pages/HomePage.js';
|
||||
import { LoginPage } from './pages/LoginPage.js';
|
||||
import { NewsEditorPage } from './pages/NewsEditorPage.js';
|
||||
import { NewsListPage } from './pages/NewsListPage.js';
|
||||
import { RegisterPage } from './pages/RegisterPage.js';
|
||||
|
||||
/**
|
||||
* Корневой компонент приложения с роутингом.
|
||||
*/
|
||||
export function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/register" element={<RegisterPage />} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/news" element={<NewsListPage />} />
|
||||
<Route path="/news/new" element={<NewsEditorPage />} />
|
||||
<Route path="/news/:id" element={<NewsEditorPage />} />
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* API-клиент: fetch-обёртка с автоматическим Authorization header
|
||||
* и обработкой 401 (событие 'auth:expired' для AuthContext).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Безопасное извлечение env-переменной Vite.
|
||||
*/
|
||||
function getEnvVar(name: string): string {
|
||||
const val: unknown = (import.meta.env as Record<string, unknown>)[name];
|
||||
return typeof val === 'string' ? val : '';
|
||||
}
|
||||
|
||||
/** Базовый URL API (через Vite proxy в dev). */
|
||||
const API_BASE: string = getEnvVar('VITE_API_URL');
|
||||
|
||||
/**
|
||||
* Текущий токен (хранится в localStorage, обновляется AuthContext).
|
||||
*/
|
||||
let authToken: string | null = localStorage.getItem('token');
|
||||
|
||||
/**
|
||||
* Устанавливает токен для последующих запросов.
|
||||
*
|
||||
* @param token — JWT-токен или null для очистки
|
||||
*/
|
||||
export function setAuthToken(token: string | null): void {
|
||||
authToken = token;
|
||||
if (token !== null) {
|
||||
localStorage.setItem('token', token);
|
||||
} else {
|
||||
localStorage.removeItem('token');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Кастомная ошибка API с кодом и сообщением.
|
||||
*/
|
||||
export class ApiClientError extends Error {
|
||||
/** HTTP статус-код. */
|
||||
readonly status: number;
|
||||
/** Код ошибки от backend. */
|
||||
readonly code: string;
|
||||
|
||||
constructor(status: number, code: string, message: string) {
|
||||
super(message);
|
||||
this.name = 'ApiClientError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Структура error body от backend.
|
||||
*/
|
||||
interface ApiErrorBody {
|
||||
error?: { code?: string; message?: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет Authorization header если токен есть.
|
||||
*/
|
||||
function buildHeaders(extra?: Record<string, string>): Record<string, string> {
|
||||
const headers: Record<string, string> = { ...extra };
|
||||
if (authToken !== null) {
|
||||
headers.Authorization = `Bearer ${authToken}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Обработка истёкшего токена (401): очищаем токен и уведомляем AuthContext.
|
||||
*
|
||||
* AuthContext подписывается на событие 'auth:expired' и сам делает logout
|
||||
* + navigate — здесь мы не трогам роутер (client.ts не знает про React).
|
||||
*/
|
||||
function handleUnauthorized(): void {
|
||||
setAuthToken(null);
|
||||
window.dispatchEvent(new Event('auth:expired'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обрабатывает ответ: при 401 очищает токен, при !ok бросает ApiClientError.
|
||||
*
|
||||
* @param res — Response из fetch
|
||||
* @returns распарсенный JSON
|
||||
*/
|
||||
async function handleResponse<T>(res: Response): Promise<T> {
|
||||
if (res.status === 401 && authToken !== null) {
|
||||
handleUnauthorized();
|
||||
}
|
||||
|
||||
const data = (await res.json().catch(() => ({}))) as unknown as ApiErrorBody & T;
|
||||
|
||||
if (!res.ok) {
|
||||
throw new ApiClientError(
|
||||
res.status,
|
||||
data.error?.code ?? 'UNKNOWN',
|
||||
data.error?.message ?? res.statusText,
|
||||
);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Выполняет fetch-запрос к API с авторизацией.
|
||||
*
|
||||
* @param path — путь относительно /api (например '/auth/login')
|
||||
* @param options — параметры fetch (method, body, headers)
|
||||
* @returns распарсенный JSON
|
||||
* @throws ApiClientError при статусе >= 400
|
||||
*/
|
||||
export async function apiFetch<T>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> {
|
||||
const extraHeaders: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (options.headers) {
|
||||
Object.assign(extraHeaders, options.headers);
|
||||
}
|
||||
const headers = buildHeaders(extraHeaders);
|
||||
const res = await fetch(`${API_BASE}/api${path}`, { ...options, headers });
|
||||
return handleResponse<T>(res);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выполняет multipart/form-data запрос (для загрузки файлов).
|
||||
*
|
||||
* @param path — путь относительно /api
|
||||
* @param formData — FormData объект
|
||||
* @returns распарсенный JSON
|
||||
*/
|
||||
export async function apiUpload<T>(path: string, formData: FormData): Promise<T> {
|
||||
const headers = buildHeaders();
|
||||
const res = await fetch(`${API_BASE}/api${path}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
});
|
||||
return handleResponse<T>(res);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Типы для API-ответов авторизации и новостей.
|
||||
*/
|
||||
|
||||
/** Ответ на регистрацию/логин. */
|
||||
export interface AuthResponse {
|
||||
token: string;
|
||||
user: { id: string; email: string };
|
||||
}
|
||||
|
||||
/** Статус новости. */
|
||||
export type NewsStatus = 'draft' | 'scheduled' | 'published';
|
||||
|
||||
/** Новость (сериализованная от backend). */
|
||||
export interface NewsItem {
|
||||
id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
status: NewsStatus;
|
||||
author: string;
|
||||
publishedAt: string | null;
|
||||
scheduledAt: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** Ответ на upload (сервер возвращает { file: { name, url } }). */
|
||||
export interface UploadResponse {
|
||||
file: { name: string; url: string };
|
||||
}
|
||||
|
||||
/** Тип уведомления. */
|
||||
export type NotificationType = 'news.created' | 'news.updated' | 'news.deleted' | 'news.scheduled' | 'news.published';
|
||||
|
||||
/** Уведомление (сериализованное от backend). */
|
||||
export interface NotificationItem {
|
||||
id: string;
|
||||
actor: string | null;
|
||||
type: NotificationType;
|
||||
news: string | null;
|
||||
title: string;
|
||||
message: string;
|
||||
isRead: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
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 type { AuthResponse } from '../api/types.js';
|
||||
|
||||
/**
|
||||
* Состояние AuthContext.
|
||||
*/
|
||||
interface AuthContextValue {
|
||||
/** JWT-токен текущего пользователя. */
|
||||
token: string | null;
|
||||
/** ID текущего пользователя. */
|
||||
userId: string | null;
|
||||
/** Email текущего пользователя. */
|
||||
userEmail: string | null;
|
||||
/** true если пользователь авторизован. */
|
||||
isAuthenticated: boolean;
|
||||
/**
|
||||
* Авторизация: login или register.
|
||||
* @param email — email
|
||||
* @param password — пароль
|
||||
* @param isRegister — true для регистрации, false для логина
|
||||
*/
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
register: (email: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Имя события об истёкшем токене (выпускается api/client.ts при 401
|
||||
* и при connect_error Socket.IO с UNAUTHORIZED).
|
||||
*/
|
||||
export const AUTH_EXPIRED_EVENT = 'auth:expired';
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
/**
|
||||
* Провайдер авторизации. Хранит token/userId в состоянии + localStorage.
|
||||
*/
|
||||
export function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
|
||||
const navigate = useNavigate();
|
||||
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'));
|
||||
const [userId, setUserId] = useState<string | null>(() => localStorage.getItem('userId'));
|
||||
const [userEmail, setUserEmail] = useState<string | null>(() => localStorage.getItem('userEmail'));
|
||||
|
||||
const handleAuth = useCallback((response: AuthResponse) => {
|
||||
setAuthToken(response.token);
|
||||
setToken(response.token);
|
||||
setUserId(response.user.id);
|
||||
setUserEmail(response.user.email);
|
||||
localStorage.setItem('userId', response.user.id);
|
||||
localStorage.setItem('userEmail', response.user.email);
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
const res = await apiFetch<AuthResponse>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
handleAuth(res);
|
||||
}, [handleAuth]);
|
||||
|
||||
const register = useCallback(async (email: string, password: string) => {
|
||||
const res = await apiFetch<AuthResponse>('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
handleAuth(res);
|
||||
}, [handleAuth]);
|
||||
|
||||
/**
|
||||
* Logout: очистка токена/данных пользователя.
|
||||
* @returns void — вызывается fire-and-forget (navigate после logout)
|
||||
*/
|
||||
const logout = useCallback((): void => {
|
||||
setAuthToken(null);
|
||||
setToken(null);
|
||||
setUserId(null);
|
||||
setUserEmail(null);
|
||||
localStorage.removeItem('userId');
|
||||
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>(() => ({
|
||||
token,
|
||||
userId,
|
||||
userEmail,
|
||||
isAuthenticated: token !== null,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
}), [token, userId, userEmail, login, register, logout]);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Хук доступа к AuthContext.
|
||||
*
|
||||
* @throws если вне AuthProvider
|
||||
*/
|
||||
export function useAuth(): AuthContextValue {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useAuth must be used within AuthProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
interface MarkdownToolbarProps {
|
||||
/** Вызывается при нажатии кнопки с именем действия. */
|
||||
readonly onAction: (action: string) => void;
|
||||
/** Вызывается при нажатии "Вставить изображение". */
|
||||
readonly onImageUpload: () => void;
|
||||
/** Вызывается при нажатии "Вставить файл". */
|
||||
readonly onFileUpload: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Панель инструментов Markdown-редактора.
|
||||
*/
|
||||
export function MarkdownToolbar({ onAction, onImageUpload, onFileUpload }: MarkdownToolbarProps) {
|
||||
return (
|
||||
<div role="toolbar" aria-label="Форматирование">
|
||||
<button type="button" title="Полужирный" onClick={() => { onAction('bold'); }}>
|
||||
<strong>B</strong>
|
||||
</button>
|
||||
<button type="button" title="Курсив" onClick={() => { onAction('italic'); }}>
|
||||
<em>I</em>
|
||||
</button>
|
||||
<button type="button" title="Заголовок" onClick={() => { onAction('heading'); }}>
|
||||
H
|
||||
</button>
|
||||
<button type="button" title="Цитата" onClick={() => { onAction('quote'); }}>
|
||||
""
|
||||
</button>
|
||||
<button type="button" title="Блок кода" onClick={() => { onAction('code'); }}>
|
||||
{'</>'}
|
||||
</button>
|
||||
<button type="button" title="Ссылка" onClick={() => { onAction('link'); }}>
|
||||
🔗
|
||||
</button>
|
||||
<button type="button" title="Вставить изображение" onClick={() => { onImageUpload(); }}>
|
||||
🖼️
|
||||
</button>
|
||||
<button type="button" title="Вставить файл" onClick={() => { onFileUpload(); }}>
|
||||
📎
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
.wrapper {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.trigger {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-radius: 6px;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: #f3f4f6;
|
||||
}
|
||||
}
|
||||
|
||||
.bell {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.badge {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -10px;
|
||||
background: #ef4444;
|
||||
color: #fff;
|
||||
font-size: 0.65rem;
|
||||
font-weight: 700;
|
||||
border-radius: 10px;
|
||||
padding: 1px 5px;
|
||||
min-width: 16px;
|
||||
text-align: center;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.panel {
|
||||
position: absolute;
|
||||
top: calc(100% + 0.625rem);
|
||||
right: 0;
|
||||
width: 340px;
|
||||
max-height: 420px;
|
||||
overflow-y: auto;
|
||||
background: #fff;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.875rem 1.25rem;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.markAll {
|
||||
background: none;
|
||||
border: none;
|
||||
color: #3b82f6;
|
||||
cursor: pointer;
|
||||
font-size: 0.8rem;
|
||||
padding: 0;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
.item {
|
||||
border-bottom: 1px solid #f9fafb;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&.unread {
|
||||
background: #f0f7ff;
|
||||
}
|
||||
|
||||
&.read {
|
||||
opacity: 0.65;
|
||||
}
|
||||
}
|
||||
|
||||
.itemBtn {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.75rem 1.25rem;
|
||||
border: none;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background 0.1s;
|
||||
|
||||
&:hover {
|
||||
background: #f9fafb;
|
||||
}
|
||||
}
|
||||
|
||||
.itemTitle {
|
||||
display: block;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
.itemMessage {
|
||||
display: block;
|
||||
font-size: 0.82rem;
|
||||
color: #4b5563;
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
|
||||
.itemTime {
|
||||
display: block;
|
||||
font-size: 0.72rem;
|
||||
color: #9ca3af;
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 2rem 1.25rem;
|
||||
text-align: center;
|
||||
color: #9ca3af;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useNotifications } from '../hooks/useNotifications.js';
|
||||
import { formatDateTime } from '../utils/formatDate.js';
|
||||
|
||||
import styles from './NotificationBell.module.scss';
|
||||
|
||||
import type { NotificationItem } from '../api/types.js';
|
||||
|
||||
|
||||
/**
|
||||
* Одиночное уведомление в списке.
|
||||
*/
|
||||
function NotificationItemRow({
|
||||
notification, onRead,
|
||||
}: {
|
||||
readonly notification: NotificationItem;
|
||||
readonly onRead: (id: string) => void;
|
||||
}) {
|
||||
const cls = notification.isRead ? styles.read : styles.unread;
|
||||
return (
|
||||
<li className={`${styles.item} ${cls}`}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.itemBtn}
|
||||
onClick={() => { if (!notification.isRead) { onRead(notification.id); } }}
|
||||
>
|
||||
<span className={styles.itemTitle}>{notification.title}</span>
|
||||
<span className={styles.itemMessage}>{notification.message}</span>
|
||||
<span className={styles.itemTime}>{formatDateTime(notification.createdAt)}</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Компонент колокольчика уведомлений.
|
||||
*
|
||||
* Отображает иконку с badge, по клику раскрывает список уведомлений.
|
||||
* Подключается к Socket.IO для real-time обновлений.
|
||||
*/
|
||||
export function NotificationBell({ token }: { readonly token: string | null }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const {
|
||||
notifications, unreadCount, markAsRead, markAllAsRead,
|
||||
} = useNotifications(token);
|
||||
|
||||
const handleMarkAsRead = (id: string): void => {
|
||||
void markAsRead(id).catch(() => { /* ignore */ });
|
||||
};
|
||||
|
||||
const handleMarkAll = (): void => {
|
||||
void markAllAsRead().catch(() => { /* ignore */ });
|
||||
};
|
||||
|
||||
if (token === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.trigger}
|
||||
onClick={() => { setOpen((v) => !v); }}
|
||||
aria-label="Уведомления"
|
||||
>
|
||||
<span className={styles.bell}>
|
||||
🔔
|
||||
{unreadCount > 0 && <span className={styles.badge}>{unreadCount > 99 ? '99+' : String(unreadCount)}</span>}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{open ? <div className={styles.panel}>
|
||||
<div className={styles.header}>
|
||||
<h3>Уведомления</h3>
|
||||
{unreadCount > 0
|
||||
? (
|
||||
<button type="button" className={styles.markAll} onClick={handleMarkAll}>
|
||||
Прочитать все
|
||||
</button>
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
|
||||
{notifications.length === 0
|
||||
? <p className={styles.empty}>Нет уведомлений</p>
|
||||
: (
|
||||
<ul className={styles.list}>
|
||||
{notifications.map((n) => (
|
||||
<NotificationItemRow key={n.id} notification={n} onRead={handleMarkAsRead} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Navigate, Outlet } from 'react-router-dom';
|
||||
|
||||
import { useAuth } from '../auth/AuthContext.js';
|
||||
|
||||
/**
|
||||
* Защищённый маршрут: перенаправляет на /login если нет авторизации.
|
||||
*/
|
||||
export function ProtectedRoute() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
import { apiFetch, apiUpload } from '../api/client.js';
|
||||
|
||||
import type { UploadResponse } from '../api/types.js';
|
||||
|
||||
/**
|
||||
* Загружает существующую новость из API.
|
||||
*/
|
||||
function useLoadNews(newsId: string | undefined, isNew: boolean) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [newsStatus, setNewsStatus] = useState<'draft' | 'scheduled' | 'published'>('draft');
|
||||
const [loading, setLoading] = useState(!isNew);
|
||||
|
||||
useEffect(() => {
|
||||
if (isNew) {
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const data = await apiFetch<{ news: { title: string; content: string; status: string } }>(`/news/${newsId}`);
|
||||
setTitle(data.news.title);
|
||||
setContent(data.news.content);
|
||||
const s = data.news.status;
|
||||
if (s === 'draft' || s === 'scheduled' || s === 'published') {
|
||||
setNewsStatus(s);
|
||||
}
|
||||
} catch {
|
||||
// Ошибка загрузки — остаёмся с пустым состоянием
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, [newsId, isNew]);
|
||||
|
||||
return { title, setTitle, content, setContent, newsStatus, loading };
|
||||
}
|
||||
|
||||
/**
|
||||
* Хук для управления состоянием и действиями редактора новости.
|
||||
*
|
||||
* @param newsId — id новости или undefined для создания
|
||||
* @returns состояние и обработчики для NewsEditorPage
|
||||
*/
|
||||
export function useNewsEditor(newsId: string | undefined) {
|
||||
const isNew = newsId === undefined;
|
||||
const { title, setTitle, content, setContent, newsStatus, loading } = useLoadNews(newsId, isNew);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [scheduleDate, setScheduleDate] = useState('');
|
||||
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 на позиции курсора. */
|
||||
const insertMarkdown = useCallback((before: string, after = ''): void => {
|
||||
const ta = textareaRef.current;
|
||||
if (ta === null) {
|
||||
return;
|
||||
}
|
||||
const start = ta.selectionStart;
|
||||
const end = ta.selectionEnd;
|
||||
const selected = content.substring(start, end);
|
||||
const newContent = content.substring(0, start) + before + selected + after + content.substring(end);
|
||||
setContent(newContent);
|
||||
requestAnimationFrame(() => {
|
||||
ta.focus();
|
||||
const newCursor = start + before.length + selected.length + after.length;
|
||||
ta.setSelectionRange(newCursor, newCursor);
|
||||
});
|
||||
}, [content, setContent]);
|
||||
|
||||
/** Сохраняет черновик. Новая новость → переход на /news. */
|
||||
const onSave = useCallback((): void => {
|
||||
runAction(async () => {
|
||||
if (isNew) {
|
||||
await apiFetch('/news', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ title, content }),
|
||||
});
|
||||
navigate('/news');
|
||||
return;
|
||||
}
|
||||
await apiFetch(`/news/${newsId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ title, content }),
|
||||
});
|
||||
setError('Сохранено ✓');
|
||||
setTimeout(() => { setError(''); }, 2000);
|
||||
}, 'Ошибка сохранения');
|
||||
}, [runAction, isNew, newsId, title, content, navigate]);
|
||||
|
||||
/** Публикует немедленно. */
|
||||
const onPublish = useCallback((): void => {
|
||||
runAction(async () => {
|
||||
if (newsId === undefined) {
|
||||
setError('Сначала сохраните черновик');
|
||||
return;
|
||||
}
|
||||
await apiFetch(`/news/${newsId}/publish`, { method: 'POST' });
|
||||
navigate('/news');
|
||||
}, 'Ошибка публикации');
|
||||
}, [runAction, newsId, navigate]);
|
||||
|
||||
/** Планирует публикацию. */
|
||||
const onSchedule = useCallback((): void => {
|
||||
runAction(async () => {
|
||||
if (newsId === undefined) {
|
||||
setError('Сначала сохраните черновик');
|
||||
return;
|
||||
}
|
||||
if (scheduleDate === '') {
|
||||
setError('Выберите дату публикации');
|
||||
return;
|
||||
}
|
||||
// datetime-local даёт local time — конвертируем в ISO (UTC) для сервера
|
||||
const iso = new Date(scheduleDate).toISOString();
|
||||
await apiFetch(`/news/${newsId}/schedule`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ scheduledAt: iso }),
|
||||
});
|
||||
navigate('/news');
|
||||
}, 'Ошибка планирования');
|
||||
}, [runAction, newsId, scheduleDate, navigate]);
|
||||
|
||||
/** Удаляет новость. */
|
||||
const onDelete = useCallback((): void => {
|
||||
runAction(async () => {
|
||||
if (newsId === undefined) {
|
||||
return;
|
||||
}
|
||||
if (!window.confirm('Удалить новость?')) {
|
||||
return;
|
||||
}
|
||||
await apiFetch(`/news/${newsId}`, { method: 'DELETE' });
|
||||
navigate('/news');
|
||||
}, 'Ошибка удаления');
|
||||
}, [runAction, newsId, navigate]);
|
||||
|
||||
/** Загружает файл и вставляет markdown-ссылку. */
|
||||
const handleFileUpload = useCallback(async (file: File, isImage: boolean): Promise<void> => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
const res = await apiUpload<UploadResponse>('/uploads', formData);
|
||||
const md = isImage
|
||||
? `\n\n`
|
||||
: `\n[${file.name}](${res.file.url})\n`;
|
||||
insertMarkdown(md);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка загрузки');
|
||||
}
|
||||
}, [insertMarkdown]);
|
||||
|
||||
/** Обработчик toolbar-кнопок. */
|
||||
const handleToolbarAction = useCallback((action: string): void => {
|
||||
if (action === 'bold') { insertMarkdown('**', '**'); }
|
||||
if (action === 'italic') { insertMarkdown('*', '*'); }
|
||||
if (action === 'heading') { insertMarkdown('# ', ''); }
|
||||
if (action === 'quote') { insertMarkdown('> ', ''); }
|
||||
if (action === 'code') { insertMarkdown('\n```\n', '\n```\n'); }
|
||||
if (action === 'link') { insertMarkdown('[', '](https://)'); }
|
||||
}, [insertMarkdown]);
|
||||
|
||||
/** Обработчик file input для изображений. */
|
||||
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file !== undefined) {
|
||||
void handleFileUpload(file, true);
|
||||
}
|
||||
e.target.value = '';
|
||||
}, [handleFileUpload]);
|
||||
|
||||
/** Обработчик file input для файлов. */
|
||||
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file !== undefined) {
|
||||
void handleFileUpload(file, false);
|
||||
}
|
||||
e.target.value = '';
|
||||
}, [handleFileUpload]);
|
||||
|
||||
return {
|
||||
isNew, title, setTitle,
|
||||
content, setContent, newsStatus,
|
||||
loading, saving, error,
|
||||
scheduleDate, setScheduleDate,
|
||||
textareaRef,
|
||||
insertMarkdown, handleToolbarAction,
|
||||
handleFileUpload, onImageChange, onFileChange,
|
||||
onSave, onPublish, onDelete, onSchedule,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
import { apiFetch } from '../api/client.js';
|
||||
|
||||
import { useSocket } from './useSocket.js';
|
||||
|
||||
import type { NotificationItem } from '../api/types.js';
|
||||
|
||||
/**
|
||||
* Хук для управления уведомлениями.
|
||||
*
|
||||
* Подписывается на Socket.IO события, загружает список уведомлений,
|
||||
* предоставляет счётчик непрочитанных и методы отметки.
|
||||
*
|
||||
* @param token — JWT токен (null если не авторизован)
|
||||
* @returns состояние и методы для NotificationBell
|
||||
*/
|
||||
export function useNotifications(token: string | null) {
|
||||
const socket = useSocket(token);
|
||||
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
||||
const [unreadCount, setUnreadCount] = useState(0);
|
||||
|
||||
/** Загружает список уведомлений и счётчик непрочитанных. */
|
||||
const fetchNotifications = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
const [listRes, countRes] = await Promise.all([
|
||||
apiFetch<{ notifications: NotificationItem[] }>('/notifications'),
|
||||
apiFetch<{ count: number }>('/notifications/unread-count'),
|
||||
]);
|
||||
setNotifications(listRes.notifications);
|
||||
setUnreadCount(countRes.count);
|
||||
} catch (err) {
|
||||
// Ошибка загрузки — логируем, user может быть offline
|
||||
console.error('Не удалось загрузить уведомления:', err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** Отмечает одно уведомление как прочитанное. */
|
||||
const markAsRead = useCallback(async (id: string): Promise<void> => {
|
||||
try {
|
||||
await apiFetch(`/notifications/${id}/read`, { method: 'PATCH' });
|
||||
setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, isRead: true } : n));
|
||||
setUnreadCount((prev) => Math.max(0, prev - 1));
|
||||
} catch (err) {
|
||||
console.error('Не удалось отметить уведомление прочитанным:', err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** Отмечает все уведомления как прочитанные. */
|
||||
const markAllAsRead = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
await apiFetch('/notifications/read-all', { method: 'POST' });
|
||||
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
|
||||
setUnreadCount(0);
|
||||
} catch (err) {
|
||||
console.error('Не удалось отметить все уведомления прочитанными:', err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Загружаем уведомления при монтировании (если авторизован)
|
||||
useEffect(() => {
|
||||
if (token !== null) {
|
||||
fetchNotifications().catch(() => { /* ignore */ });
|
||||
}
|
||||
}, [token, fetchNotifications]);
|
||||
|
||||
// Подписываемся на real-time уведомления
|
||||
useEffect(() => {
|
||||
const onNotification = (data: NotificationItem): void => {
|
||||
setNotifications((prev) => [data, ...prev]);
|
||||
setUnreadCount((prev) => prev + 1);
|
||||
};
|
||||
|
||||
if (socket !== null) {
|
||||
socket.on('notification', onNotification);
|
||||
return () => {
|
||||
socket.off('notification', onNotification);
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}, [socket]);
|
||||
|
||||
return {
|
||||
notifications,
|
||||
unreadCount,
|
||||
fetchNotifications,
|
||||
markAsRead,
|
||||
markAllAsRead,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
|
||||
import { AUTH_EXPIRED_EVENT } from '../auth/AuthContext.js';
|
||||
|
||||
/**
|
||||
* Подключается к Socket.IO серверу с JWT-аутентификацией.
|
||||
*
|
||||
* При connect_error с UNAUTHORIZED (истёкший/невалидный JWT) — выпускает
|
||||
* событие 'auth:expired': AuthContext делает logout + navigate.
|
||||
* Это прерывает бесконечный reconnect loop с мёртвым токеном.
|
||||
*
|
||||
* @param token — JWT токен пользователя
|
||||
* @param url — URL Socket.IO сервера (по умолчанию — текущий origin)
|
||||
* @returns socket или null (если не подключено)
|
||||
*/
|
||||
export function useSocket(token: string | null, url?: string): Socket | null {
|
||||
const [socket, setSocket] = useState<Socket | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (token === null || token === '') {
|
||||
setSocket(null);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const socketUrl = url ?? window.location.origin;
|
||||
const newSocket = io(socketUrl, {
|
||||
auth: { token },
|
||||
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);
|
||||
|
||||
return () => {
|
||||
newSocket.off('connect_error', onConnectError);
|
||||
newSocket.disconnect();
|
||||
setSocket(null);
|
||||
};
|
||||
}, [token, url]);
|
||||
|
||||
return socket;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createRoot } from 'react-dom/client';
|
||||
|
||||
import { App } from './App.js';
|
||||
import './styles/global.scss';
|
||||
|
||||
const root = document.getElementById('root');
|
||||
if (root) {
|
||||
createRoot(root).render(<App />);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
.page {
|
||||
max-width: 640px;
|
||||
margin: 3rem auto;
|
||||
padding: 3rem 2.5rem;
|
||||
text-align: center;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
|
||||
|
||||
p {
|
||||
margin-bottom: 1.5rem;
|
||||
color: #4b5563;
|
||||
}
|
||||
}
|
||||
|
||||
.nav {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.875rem 2rem;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
|
||||
|
||||
a {
|
||||
margin-right: 1.25rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.navRight {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
|
||||
button {
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
import { useAuth } from '../auth/AuthContext.js';
|
||||
import { NotificationBell } from '../components/NotificationBell.js';
|
||||
|
||||
import styles from './HomePage.module.scss';
|
||||
|
||||
/**
|
||||
* Главная страница (защищена ProtectedRoute).
|
||||
* Показывает email пользователя, навигацию и кнопку logout.
|
||||
*/
|
||||
export function HomePage() {
|
||||
const { userEmail, token, logout } = useAuth();
|
||||
|
||||
return (
|
||||
<>
|
||||
<nav className={styles.nav}>
|
||||
<span>News Editor — {userEmail}</span>
|
||||
<div className={styles.navRight}>
|
||||
<NotificationBell token={token} />
|
||||
<Link to="/news">Мои новости</Link>
|
||||
<button type="button" onClick={logout}>
|
||||
Выйти
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div className={styles.page}>
|
||||
<h1>News Editor</h1>
|
||||
<p>Добро пожаловать, {userEmail}!</p>
|
||||
<Link to="/news" className="btn btn-primary">
|
||||
Перейти к новостям
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { useAuth } from '../auth/AuthContext.js';
|
||||
|
||||
import styles from './auth.module.scss';
|
||||
|
||||
/**
|
||||
* Страница логина.
|
||||
*/
|
||||
export function LoginPage() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = (e: FormEvent): void => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
login(email, password)
|
||||
.then(() => { navigate('/'); })
|
||||
.catch((err: unknown) => {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка логина');
|
||||
})
|
||||
.finally(() => { setLoading(false); });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<h1 className={styles.title}>Вход</h1>
|
||||
<form className={styles.form} onSubmit={handleSubmit}>
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="email">Email</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => { setEmail(e.target.value); }}
|
||||
required
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="password">Пароль</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => { setPassword(e.target.value); }}
|
||||
required
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" className={`btn btn-primary ${styles.submit}`} disabled={loading}>
|
||||
{loading ? 'Вход...' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
<p className={styles.switch}>
|
||||
Нет аккаунта?{' '}
|
||||
<Link to="/register">Зарегистрироваться</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
.page {
|
||||
max-width: 820px;
|
||||
margin: 2rem auto;
|
||||
padding: 2rem 2.5rem;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 2rem;
|
||||
padding-bottom: 1.25rem;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem 1rem;
|
||||
|
||||
h1 {
|
||||
margin-bottom: 0;
|
||||
font-size: 1.4rem;
|
||||
margin-right: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 0.625rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.titleInput {
|
||||
font-size: 1.3rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1.5rem;
|
||||
border: none;
|
||||
border-bottom: 2px solid #e5e7eb;
|
||||
border-radius: 0;
|
||||
padding: 0.625rem 0;
|
||||
|
||||
&:focus {
|
||||
border-bottom-color: #2563eb;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.scheduleRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.25rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: #fffbeb;
|
||||
border: 1px solid #fde68a;
|
||||
border-radius: 8px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
label {
|
||||
font-size: 0.9rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
input {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: #f9fafb;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-bottom: none;
|
||||
border-radius: 6px 6px 0 0;
|
||||
flex-wrap: wrap;
|
||||
|
||||
button {
|
||||
padding: 0.4rem 0.65rem;
|
||||
font-size: 0.88rem;
|
||||
background: transparent;
|
||||
color: #374151;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
|
||||
&:hover {
|
||||
background: #e5e7eb;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.textarea {
|
||||
min-height: 320px;
|
||||
resize: vertical;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.7;
|
||||
border-radius: 0 0 6px 6px;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.preview {
|
||||
padding: 1.5rem 2rem;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
background: #fafafa;
|
||||
min-height: 320px;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { useRef, useState, type ChangeEvent, type RefObject } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import rehypeSanitize from 'rehype-sanitize';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
|
||||
import { MarkdownToolbar } from '../components/MarkdownToolbar.js';
|
||||
import { useNewsEditor } from '../hooks/useNewsEditor.js';
|
||||
|
||||
import styles from './NewsEditorPage.module.scss';
|
||||
|
||||
/**
|
||||
* Панель действий редактора (кнопки).
|
||||
*/
|
||||
function EditorActions({
|
||||
isNew, isPublished, saving, onSave, onPublish, onDelete,
|
||||
}: {
|
||||
readonly isNew: boolean;
|
||||
readonly isPublished: boolean;
|
||||
readonly saving: boolean;
|
||||
readonly onSave: () => void;
|
||||
readonly onPublish: () => void;
|
||||
readonly onDelete: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className={styles.actions}>
|
||||
<button type="button" className="btn btn-primary" onClick={onSave} disabled={saving}>
|
||||
Сохранить
|
||||
</button>
|
||||
{!isNew && !isPublished
|
||||
? (
|
||||
<button type="button" className="btn btn-publish" onClick={onPublish} disabled={saving}>
|
||||
Опубликовать
|
||||
</button>
|
||||
)
|
||||
: null}
|
||||
{!isNew
|
||||
? (
|
||||
<button type="button" className="btn btn-delete" onClick={onDelete} disabled={saving}>
|
||||
Удалить
|
||||
</button>
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Строка отложенной публикации.
|
||||
*/
|
||||
function ScheduleRow({
|
||||
scheduleDate, setScheduleDate, saving, onSchedule,
|
||||
}: {
|
||||
readonly scheduleDate: string;
|
||||
readonly setScheduleDate: (v: string) => void;
|
||||
readonly saving: boolean;
|
||||
readonly onSchedule: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className={styles.scheduleRow}>
|
||||
<label>
|
||||
Отложенная публикация:{' '}
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={scheduleDate}
|
||||
onChange={(e) => { setScheduleDate(e.target.value); }}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-schedule"
|
||||
onClick={onSchedule}
|
||||
disabled={saving || scheduleDate === ''}
|
||||
>
|
||||
Запланировать
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Форма редактора (toolbar + textarea + file inputs).
|
||||
*/
|
||||
function EditorForm({
|
||||
content, setContent, textareaRef, onAction, onImageUpload, onFileUpload, onImageChange, onFileChange,
|
||||
imageInputRef, fileInputRef,
|
||||
}: {
|
||||
readonly content: string;
|
||||
readonly setContent: (v: string) => void;
|
||||
readonly textareaRef: RefObject<HTMLTextAreaElement>;
|
||||
readonly onAction: (action: string) => void;
|
||||
readonly onImageUpload: () => void;
|
||||
readonly onFileUpload: () => void;
|
||||
readonly onImageChange: (e: ChangeEvent<HTMLInputElement>) => void;
|
||||
readonly onFileChange: (e: ChangeEvent<HTMLInputElement>) => void;
|
||||
readonly imageInputRef: RefObject<HTMLInputElement>;
|
||||
readonly fileInputRef: RefObject<HTMLInputElement>;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div className={styles.toolbar}>
|
||||
<MarkdownToolbar onAction={onAction} onImageUpload={onImageUpload} onFileUpload={onFileUpload} />
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className={styles.textarea}
|
||||
value={content}
|
||||
onChange={(e) => { setContent(e.target.value); }}
|
||||
placeholder="Напишите текст в Markdown..."
|
||||
rows={20}
|
||||
/>
|
||||
|
||||
<input
|
||||
ref={imageInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||
style={{ display: 'none' }}
|
||||
onChange={onImageChange}
|
||||
/>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
style={{ display: 'none' }}
|
||||
onChange={onFileChange}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Предпросмотр markdown.
|
||||
*/
|
||||
function EditorPreview({ content }: { readonly content: string }) {
|
||||
if (content === '') {
|
||||
return <div className={styles.preview}><p className="empty">Нет контента для предпросмотра</p></div>;
|
||||
}
|
||||
return (
|
||||
<div className={`${styles.preview} markdown-body`}>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSanitize]}>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Страница редактирования/создания новости с Markdown-редактором.
|
||||
*/
|
||||
export function NewsEditorPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [showPreview, setShowPreview] = useState(id !== undefined);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const imageInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const editor = useNewsEditor(id);
|
||||
|
||||
const {
|
||||
isNew, title, setTitle, content, setContent, newsStatus,
|
||||
loading, saving, error,
|
||||
scheduleDate, setScheduleDate, textareaRef,
|
||||
handleToolbarAction, onImageChange, onFileChange,
|
||||
onSave, onPublish, onDelete, onSchedule,
|
||||
} = editor;
|
||||
|
||||
if (loading) {
|
||||
return <p className="loading">Загрузка...</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={styles.header}>
|
||||
<Link to="/news" className="btn btn-back">← Назад</Link>
|
||||
<h1>{isNew ? 'Новая новость' : 'Редактирование'}</h1>
|
||||
<EditorActions
|
||||
isNew={isNew}
|
||||
isPublished={newsStatus === 'published'}
|
||||
saving={saving}
|
||||
onSave={onSave}
|
||||
onPublish={onPublish}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
{newsStatus !== 'published'
|
||||
? (
|
||||
<button type="button" className="btn" onClick={() => { setShowPreview((v) => !v); }}>
|
||||
{showPreview ? 'Редактор' : 'Предпросмотр'}
|
||||
</button>
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
|
||||
{error !== '' && <p className="error">{error}</p>}
|
||||
|
||||
<input
|
||||
type="text"
|
||||
className={styles.titleInput}
|
||||
placeholder="Заголовок..."
|
||||
value={title}
|
||||
onChange={(e) => { setTitle(e.target.value); }}
|
||||
/>
|
||||
|
||||
{!isNew && newsStatus !== 'published'
|
||||
? (
|
||||
<ScheduleRow
|
||||
scheduleDate={scheduleDate}
|
||||
setScheduleDate={setScheduleDate}
|
||||
saving={saving}
|
||||
onSchedule={onSchedule}
|
||||
/>
|
||||
)
|
||||
: null}
|
||||
|
||||
{showPreview
|
||||
? <EditorPreview content={content} />
|
||||
: (
|
||||
<EditorForm
|
||||
content={content}
|
||||
setContent={setContent}
|
||||
textareaRef={textareaRef}
|
||||
onAction={handleToolbarAction}
|
||||
onImageUpload={() => { imageInputRef.current?.click(); }}
|
||||
onFileUpload={() => { fileInputRef.current?.click(); }}
|
||||
onImageChange={onImageChange}
|
||||
onFileChange={onFileChange}
|
||||
imageInputRef={imageInputRef}
|
||||
fileInputRef={fileInputRef}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
.page {
|
||||
max-width: 720px;
|
||||
margin: 2rem auto;
|
||||
padding: 2rem 2.5rem;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 1.5rem;
|
||||
padding-bottom: 1rem;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
|
||||
h1 {
|
||||
font-size: 1.4rem;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
padding: 1rem 1.25rem;
|
||||
background: #fafbfc;
|
||||
border: 1px solid #f3f4f6;
|
||||
border-radius: 8px;
|
||||
transition: box-shadow 0.15s, border-color 0.15s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
|
||||
border-color: #e5e7eb;
|
||||
}
|
||||
}
|
||||
|
||||
.cardBody {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cardTitle {
|
||||
font-weight: 600;
|
||||
display: block;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.cardPreview {
|
||||
font-size: 0.85rem;
|
||||
color: #6b7280;
|
||||
line-height: 1.4;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.cardMeta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 0.35rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cardDate {
|
||||
font-size: 0.78rem;
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 0.72rem;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
|
||||
&.draft {
|
||||
background: #f3f4f6;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
&.scheduled {
|
||||
background: #fef3c7;
|
||||
color: #92400e;
|
||||
}
|
||||
|
||||
&.published {
|
||||
background: #d1fae5;
|
||||
color: #065f46;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
import { apiFetch } from '../api/client.js';
|
||||
import { formatDateTime } from '../utils/formatDate.js';
|
||||
|
||||
import styles from './NewsListPage.module.scss';
|
||||
|
||||
import type { NewsItem } from '../api/types.js';
|
||||
|
||||
|
||||
/**
|
||||
* Страница со списком новостей текущего пользователя.
|
||||
*/
|
||||
export function NewsListPage() {
|
||||
const [news, setNews] = useState<NewsItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
/** Загружает список новостей. */
|
||||
async function loadNews(): Promise<void> {
|
||||
try {
|
||||
const data = await apiFetch<{ news: NewsItem[] }>('/news');
|
||||
setNews(data.news);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка загрузки');
|
||||
// При 401 api-клиент уже очистил токен и выпустил auth:expired —
|
||||
// AuthContext сделает logout + navigate('/login')
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
loadNews().catch(() => { /* ошибки обработаны внутри loadNews */ });
|
||||
}, []);
|
||||
|
||||
if (loading) {
|
||||
return <p className="loading">Загрузка...</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={styles.header}>
|
||||
<h1>Мои новости</h1>
|
||||
<Link to="/news/new" className="btn btn-primary">
|
||||
+ Создать
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{error !== '' && <p className="error">{error}</p>}
|
||||
|
||||
{news.length === 0
|
||||
? <p className="empty">Нет новостей. Создайте первую!</p>
|
||||
: (
|
||||
<ul className={styles.list}>
|
||||
{news.map((item) => (
|
||||
<li key={item.id} className={styles.card}>
|
||||
<div className={styles.cardBody}>
|
||||
<Link to={`/news/${item.id}`} className={styles.cardTitle}>
|
||||
{item.title !== '' ? item.title : '(без названия)'}
|
||||
</Link>
|
||||
{item.content !== '' && (
|
||||
<p className={styles.cardPreview}>
|
||||
{item.content.replace(/[#*`[\]!\n]/g, '').slice(0, 120)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.cardMeta}>
|
||||
<span className={`${styles.badge} ${styles[item.status]}`}>{item.status}</span>
|
||||
<span className={styles.cardDate}>
|
||||
{formatDateTime(item.updatedAt)}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { useAuth } from '../auth/AuthContext.js';
|
||||
|
||||
import styles from './auth.module.scss';
|
||||
|
||||
/**
|
||||
* Страница регистрации.
|
||||
*/
|
||||
export function RegisterPage() {
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = (e: FormEvent): void => {
|
||||
e.preventDefault();
|
||||
if (password !== confirmPassword) {
|
||||
setError('Пароли не совпадают');
|
||||
return;
|
||||
}
|
||||
setError('');
|
||||
setLoading(true);
|
||||
register(email, password)
|
||||
.then(() => { navigate('/'); })
|
||||
.catch((err: unknown) => {
|
||||
setError(err instanceof Error ? err.message : 'Ошибка регистрации');
|
||||
})
|
||||
.finally(() => { setLoading(false); });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<h1 className={styles.title}>Регистрация</h1>
|
||||
<form className={styles.form} onSubmit={handleSubmit}>
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="email">Email</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => { setEmail(e.target.value); }}
|
||||
required
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="password">Пароль</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => { setPassword(e.target.value); }}
|
||||
required
|
||||
minLength={6}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.group}>
|
||||
<label htmlFor="confirmPassword">Повторите пароль</label>
|
||||
<input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => { setConfirmPassword(e.target.value); }}
|
||||
required
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" className={`btn btn-primary ${styles.submit}`} disabled={loading}>
|
||||
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
<p className={styles.switch}>
|
||||
Уже есть аккаунт?{' '}
|
||||
<Link to="/login">Войти</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
.page {
|
||||
max-width: 400px;
|
||||
margin: 3rem auto;
|
||||
padding: 2rem 2.5rem;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 1.4rem;
|
||||
margin-bottom: 1.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
|
||||
label {
|
||||
font-weight: 500;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.submit {
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.switch {
|
||||
margin-top: 1.5rem;
|
||||
text-align: center;
|
||||
font-size: 0.9rem;
|
||||
color: #6b7280;
|
||||
|
||||
a {
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// Глобальные стили News Editor (base + shared utilities)
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #1a1a2e;
|
||||
background: #f0f2f5;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #2563eb;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin-bottom: 1rem;
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
|
||||
input,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 6px;
|
||||
font-size: 0.95rem;
|
||||
font-family: inherit;
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
border-color: #2563eb;
|
||||
box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15);
|
||||
}
|
||||
}
|
||||
|
||||
// === Shared: Кнопки ===
|
||||
.btn {
|
||||
display: inline-block;
|
||||
padding: 0.5rem 1.2rem;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.95rem;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
background: #e5e7eb;
|
||||
color: #1a1a2e;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: #d1d5db;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
&-primary {
|
||||
background: #2563eb;
|
||||
color: #fff;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
}
|
||||
|
||||
&-publish {
|
||||
background: #16a34a;
|
||||
color: #fff;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: #15803d;
|
||||
}
|
||||
}
|
||||
|
||||
&-schedule {
|
||||
background: #f59e0b;
|
||||
color: #fff;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: #d97706;
|
||||
}
|
||||
}
|
||||
|
||||
&-delete {
|
||||
background: #dc2626;
|
||||
color: #fff;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: #b91c1c;
|
||||
}
|
||||
}
|
||||
|
||||
&-back {
|
||||
background: transparent;
|
||||
color: #2563eb;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: #eff6ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Shared: Error / Loading / Empty ===
|
||||
.error {
|
||||
color: #dc2626;
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 1rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: #fef2f2;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #fecaca;
|
||||
}
|
||||
|
||||
.loading,
|
||||
.empty {
|
||||
color: #6b7280;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
// === Markdown body (используется в preview) ===
|
||||
.markdown-body {
|
||||
h1, h2, h3 {
|
||||
margin: 1.25rem 0 0.5rem;
|
||||
|
||||
&:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
p {
|
||||
margin-bottom: 0.875rem;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 4px solid #2563eb;
|
||||
padding: 0.5rem 1rem;
|
||||
margin: 1rem 0;
|
||||
color: #4b5563;
|
||||
background: #f8faff;
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
|
||||
code {
|
||||
background: #f3f4f6;
|
||||
padding: 0.15rem 0.4rem;
|
||||
border-radius: 3px;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: #1f2937;
|
||||
color: #e5e7eb;
|
||||
padding: 1.25rem 1.5rem;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
margin: 1rem 0;
|
||||
|
||||
code {
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin: 1rem 0;
|
||||
|
||||
th, td {
|
||||
border: 1px solid #e5e7eb;
|
||||
padding: 0.6rem 0.75rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
th {
|
||||
background: #f9fafb;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}`;
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -9,6 +9,12 @@ import react from '@vitejs/plugin-react';
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
host: true,
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:3000',
|
||||
'/uploads': 'http://localhost:3000',
|
||||
'/socket.io': { target: 'http://localhost:3000', ws: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
services:
|
||||
mongo:
|
||||
image: mongo:7
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- mongo_data:/data/db
|
||||
healthcheck:
|
||||
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
server:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: server/Dockerfile
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
mongo:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
PORT: 3000
|
||||
MONGODB_URI: mongodb://mongo:27017/news-editor
|
||||
JWT_SECRET: ${JWT_SECRET:?Set JWT_SECRET in .env}
|
||||
JWT_EXPIRES_IN: 7d
|
||||
CLIENT_ORIGIN: ${CLIENT_ORIGIN:-http://localhost:8080}
|
||||
MAX_UPLOAD_SIZE: 20971520
|
||||
SCHEDULER_INTERVAL_MS: 20000
|
||||
UPLOAD_DIR: /app/uploads
|
||||
volumes:
|
||||
- uploads_data:/app/uploads
|
||||
|
||||
client:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: client/Dockerfile
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- server
|
||||
ports:
|
||||
- "${PORT:-8080}:80"
|
||||
|
||||
volumes:
|
||||
mongo_data:
|
||||
uploads_data:
|
||||
@@ -9,3 +9,4 @@ CLIENT_ORIGIN=http://localhost:5173
|
||||
|
||||
UPLOAD_DIR=uploads
|
||||
MAX_UPLOAD_SIZE=20971520
|
||||
SCHEDULER_INTERVAL_MS=20000
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Stage 1: Build
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY server/package*.json ./
|
||||
RUN npm ci
|
||||
COPY server/ ./
|
||||
RUN npm run build
|
||||
|
||||
# Stage 2: Production
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
COPY server/package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY --from=build /app/package.json ./
|
||||
EXPOSE 3000
|
||||
CMD ["node", "dist/src/server.js"]
|
||||
+102
-8
@@ -13,7 +13,7 @@ import tseslint from 'typescript-eslint';
|
||||
const CONFIG_ROOT = import.meta.dirname;
|
||||
|
||||
const TEST_FILES = ['**/*.{test,spec}.ts', 'tests/**/*.{ts,mts,cts}'];
|
||||
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/eslint.config.*'];
|
||||
const CONFIG_AND_SCRIPT_FILES = ['**/*.config.{ts,mts,cts}', '**/eslint.config.*', '**/vite.config.*'];
|
||||
|
||||
export default defineConfig(
|
||||
/* ── Глобальные игноры ─────────────────────────────────────── */
|
||||
@@ -30,8 +30,11 @@ export default defineConfig(
|
||||
{
|
||||
name: 'server/linter-policy',
|
||||
linterOptions: {
|
||||
noInlineConfig: false,
|
||||
// Inline-директивы (eslint-disable и т.п.) в коде запрещены.
|
||||
// Единственный способ отключить правило — file-level override в этом конфиге.
|
||||
noInlineConfig: true,
|
||||
reportUnusedDisableDirectives: 'error',
|
||||
reportUnusedInlineConfigs: 'error',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -227,12 +230,6 @@ export default defineConfig(
|
||||
'newlines-between': 'always',
|
||||
}],
|
||||
|
||||
/* Запрет необъяснённых disable-директив */
|
||||
'@eslint-community/eslint-comments/disable-enable-pair': ['error', { allowWholeFile: false }],
|
||||
'@eslint-community/eslint-comments/no-aggregating-enable': 'error',
|
||||
'@eslint-community/eslint-comments/no-duplicate-disable': 'error',
|
||||
'@eslint-community/eslint-comments/no-unlimited-disable': 'error',
|
||||
'@eslint-community/eslint-comments/require-description': ['error', { ignore: ['eslint-enable'] }],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -256,9 +253,106 @@ 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',
|
||||
// Тесты извлекают поля из unknown-ответов (supertest body)
|
||||
'@typescript-eslint/consistent-type-assertions': 'off',
|
||||
'@typescript-eslint/no-unsafe-type-assertion': 'off',
|
||||
'@typescript-eslint/no-unsafe-return': 'off',
|
||||
},
|
||||
},
|
||||
|
||||
/* ── Файловые исключения (единственный способ отключить правило) ── */
|
||||
{
|
||||
name: 'server/express-assertions',
|
||||
files: [
|
||||
'src/routes/news.routes.ts',
|
||||
'src/routes/auth.routes.ts',
|
||||
'src/routes/upload.routes.ts',
|
||||
'src/routes/notification.routes.ts',
|
||||
'src/middleware/auth.middleware.ts',
|
||||
],
|
||||
rules: {
|
||||
// Express req расширяется middleware — assertion неизбежен
|
||||
'@typescript-eslint/consistent-type-assertions': 'off',
|
||||
'@typescript-eslint/no-unsafe-type-assertion': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'server/auth-middleware',
|
||||
files: ['src/middleware/auth.middleware.ts'],
|
||||
rules: {
|
||||
// req.user устанавливается auth middleware (стандартный паттерн Express)
|
||||
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['req'] }],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'server/error-middleware',
|
||||
files: ['src/middleware/error.middleware.ts'],
|
||||
rules: {
|
||||
// Сигнатура ErrorRequestHandler требует 4 аргумента
|
||||
'@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/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',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'server/auth-mongoose',
|
||||
files: ['src/routes/auth.routes.ts'],
|
||||
rules: {
|
||||
// Mongoose документ (без IUser-интерфейса) — no-unsafe срабатывает
|
||||
'@typescript-eslint/no-unsafe-argument': 'off',
|
||||
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||
// Email-regex на ограниченном input (после trim)
|
||||
'sonarjs/slow-regex': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'server/upload-routes',
|
||||
files: ['src/routes/upload.routes.ts'],
|
||||
rules: {
|
||||
// asyncHandler требует async-обёртку
|
||||
'@typescript-eslint/require-await': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'server/scheduler',
|
||||
files: ['src/services/publicationScheduler.service.ts'],
|
||||
rules: {
|
||||
// Логирование факта публикации в production
|
||||
'no-console': ['error', { allow: ['error', 'warn', 'log'] }],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'server/socket',
|
||||
files: ['src/socket/socketServer.ts'],
|
||||
rules: {
|
||||
// socket.userId — стандартный паттерн Socket.IO (socket.data)
|
||||
'no-param-reassign': ['error', { props: true, ignorePropertyModificationsFor: ['socket'] }],
|
||||
// socket.join — fire-and-forget (void)
|
||||
'@typescript-eslint/no-floating-promises': 'off',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
+24
-10
@@ -7,37 +7,51 @@ 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 { createNewsRouter } from './routes/news.routes.js';
|
||||
import notificationRouter from './routes/notification.routes.js';
|
||||
import uploadRouter from './routes/upload.routes.js';
|
||||
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/**
|
||||
* Параметры для создания приложения.
|
||||
*/
|
||||
interface CreateAppOptions {
|
||||
/** Экземпляр Socket.IO server (передаётся в news routes для emit). */
|
||||
readonly io?: SocketIOServer;
|
||||
/** Дополнительные middleware (тесты). */
|
||||
readonly extraMiddleware?: express.RequestHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Создаёт и настраивает Express-приложение.
|
||||
*
|
||||
* Функция (а не готовый экземпляр) позволяет тестам создавать
|
||||
* независимые приложения без побочных эффектов.
|
||||
*
|
||||
* @param extraMiddleware — дополнительные middleware, подключаемые
|
||||
* после роутеров и до терминальных обработчиков (используется в тестах
|
||||
* для проверки error middleware на контролируемых путях)
|
||||
* @param options — параметры (io, extraMiddleware)
|
||||
* @returns настроенное Express-приложение
|
||||
*/
|
||||
export function createApp(extraMiddleware?: express.RequestHandler): express.Express {
|
||||
export function createApp(options?: CreateAppOptions): express.Express {
|
||||
const app = express();
|
||||
const { io, extraMiddleware } = options ?? {};
|
||||
|
||||
// Security headers
|
||||
app.use(helmet());
|
||||
|
||||
// CORS — whitelist из CLIENT_ORIGIN
|
||||
app.use(cors({ origin: env.clientOrigin }));
|
||||
app.use(cors({ origin: env.clientOrigins }));
|
||||
|
||||
// Парсинг тела запроса
|
||||
app.use(json());
|
||||
app.use(urlencoded({ extended: true }));
|
||||
|
||||
// Статические загруженные файлы (Phase 5)
|
||||
// app.use('/uploads', express.static(env.uploadDir));
|
||||
// Статические загруженные файлы
|
||||
app.use('/uploads', express.static(env.uploadDir));
|
||||
|
||||
// API-маршруты
|
||||
app.use('/api', healthRouter);
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/news', createNewsRouter(io));
|
||||
app.use('/api/notifications', notificationRouter);
|
||||
app.use('/api/uploads', uploadRouter);
|
||||
|
||||
// Дополнительные middleware (тестовые маршруты, заглушки)
|
||||
if (extraMiddleware) {
|
||||
|
||||
@@ -27,6 +27,7 @@ loadDotenv({ path: path.join(SERVER_ROOT, '.env') });
|
||||
* @property {string} clientOrigin — разрешённый origin для CORS
|
||||
* @property {string} uploadDir — каталог для загружаемых файлов (абсолютный путь)
|
||||
* @property {number} maxUploadSize — максимальный размер файла в байтах
|
||||
* @property {number} schedulerIntervalMs — интервал опроса scheduler в мс
|
||||
*/
|
||||
export interface Env {
|
||||
readonly nodeEnv: string;
|
||||
@@ -35,8 +36,10 @@ export interface Env {
|
||||
readonly jwtSecret: string;
|
||||
readonly jwtExpiresIn: string;
|
||||
readonly clientOrigin: string;
|
||||
readonly clientOrigins: string[];
|
||||
readonly uploadDir: string;
|
||||
readonly maxUploadSize: number;
|
||||
readonly schedulerIntervalMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -84,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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает все переменные окружения с валидацией.
|
||||
*
|
||||
@@ -91,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',
|
||||
@@ -102,9 +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',
|
||||
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: 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,8 +32,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 для последующих обработчиков
|
||||
(req as AuthenticatedRequest).user = { id: payload.id };
|
||||
req.user = { id: payload.id };
|
||||
next();
|
||||
} catch {
|
||||
next(new ApiError(401, 'UNAUTHORIZED', 'Невалидный или истёкший токен'));
|
||||
|
||||
@@ -23,8 +23,12 @@ function errorMessageOf(err: unknown): string {
|
||||
* `{ error: { code, message } }`, а непредвиденные ошибки — в 500.
|
||||
* В production stack trace клиенту не возвращается.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- сигнатура Express требует 4 аргумента
|
||||
export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
// Если ответ уже отправлен (Socket.IO) — не дублируем
|
||||
if (res.headersSent) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ожидаемая ошибка — возвращаем её статус и код
|
||||
if (err instanceof ApiError) {
|
||||
res.status(err.status).json({ error: { code: err.code, message: err.message } });
|
||||
|
||||
@@ -8,6 +8,10 @@ import type { NextFunction, Request, Response } from 'express';
|
||||
* Вызывается после всех маршрутизаторов и передаёт ошибку 404
|
||||
* в централизованный error middleware.
|
||||
*/
|
||||
export function notFoundHandler(req: Request, _res: Response, next: NextFunction): void {
|
||||
export function notFoundHandler(req: Request, res: Response, next: NextFunction): void {
|
||||
// Если ответ уже отправлен (Socket.IO) — не дублируем
|
||||
if (res.headersSent) {
|
||||
return;
|
||||
}
|
||||
next(new ApiError(404, 'NOT_FOUND', `Маршрут не найден: ${req.method} ${req.originalUrl}`));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import multer, { type FileFilterCallback } from 'multer';
|
||||
|
||||
import { env } from '../config/env.js';
|
||||
|
||||
/**
|
||||
* Разрешённые MIME-типы для загрузки.
|
||||
*/
|
||||
const ALLOWED_MIME_TYPES = new Set([
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/gif',
|
||||
'image/webp',
|
||||
'application/pdf',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Расширения файлов для генерации safe filename.
|
||||
* Ключ — MIME-тип, значение — расширение.
|
||||
*/
|
||||
const MIME_EXTENSIONS: Record<string, string> = {
|
||||
'image/jpeg': 'jpg',
|
||||
'image/png': 'png',
|
||||
'image/gif': 'gif',
|
||||
'image/webp': 'webp',
|
||||
'application/pdf': 'pdf',
|
||||
'application/msword': 'doc',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
|
||||
};
|
||||
|
||||
/**
|
||||
* Проверка MIME-типа загружаемого файла.
|
||||
*
|
||||
* @param _req — запрос Express
|
||||
* @param file — файл из multer
|
||||
* @param cb — callback multer
|
||||
*/
|
||||
function checkMimeType(_req: unknown, file: { mimetype: string }, cb: FileFilterCallback): void {
|
||||
if (ALLOWED_MIME_TYPES.has(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
const err = new Error(
|
||||
`Недопустимый тип файла: ${file.mimetype}. Разрешены: изображения (jpg, png, gif, webp), PDF, Word (doc, docx)`,
|
||||
);
|
||||
cb(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Настройка multer:
|
||||
* - diskStorage в env.uploadDir
|
||||
* - UUID-based filenames (без пользовательского имени)
|
||||
* - MIME whitelist
|
||||
* - Size limit из env
|
||||
*/
|
||||
export const upload = multer({
|
||||
storage: multer.diskStorage({
|
||||
destination: (_req, _file, cb) => {
|
||||
cb(null, env.uploadDir);
|
||||
},
|
||||
filename: (_req, file, cb) => {
|
||||
// Генерируем безопасное имя: UUID + расширение по MIME
|
||||
const ext = MIME_EXTENSIONS[file.mimetype] ?? 'bin';
|
||||
cb(null, `${randomUUID()}.${ext}`);
|
||||
},
|
||||
}),
|
||||
limits: {
|
||||
fileSize: env.maxUploadSize,
|
||||
files: 1,
|
||||
},
|
||||
fileFilter: checkMimeType,
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
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<INews>;
|
||||
|
||||
const newsSchema = new Schema<INews>(
|
||||
{
|
||||
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,
|
||||
},
|
||||
);
|
||||
|
||||
// Индекс для scheduler: поиск scheduled новостей с прошлым scheduledAt
|
||||
newsSchema.index({ status: 1, scheduledAt: 1 });
|
||||
|
||||
const News = model<INews>('News', newsSchema);
|
||||
|
||||
export default News;
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Schema, model, type HydratedDocument, type Types } from 'mongoose';
|
||||
|
||||
/** Тип уведомления о действиях с новостью. */
|
||||
export type NotificationType = 'news.created' | 'news.updated' | 'news.deleted' | 'news.scheduled' | 'news.published';
|
||||
|
||||
export interface INotification {
|
||||
/** Получатель уведомления. */
|
||||
user: Types.ObjectId;
|
||||
/** Кто совершил действие (может совпадать с user). */
|
||||
actor: Types.ObjectId | null;
|
||||
/** Тип события. */
|
||||
type: NotificationType;
|
||||
/** Ссылка на новость (если применимо). */
|
||||
news: Types.ObjectId | null;
|
||||
/** Заголовок уведомления. */
|
||||
title: string;
|
||||
/** Тело сообщения. */
|
||||
message: string;
|
||||
/** Прочитано ли. */
|
||||
isRead: boolean;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export type NotificationDocument = HydratedDocument<INotification>;
|
||||
|
||||
const notificationSchema = new Schema<INotification>(
|
||||
{
|
||||
user: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
required: [true, 'Получатель уведомления обязателен'],
|
||||
},
|
||||
actor: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'User',
|
||||
// Могут совпадать с user (однопользовательский сценарий) или
|
||||
// быть null (системные уведомления). Mongoose кастит string → ObjectId.
|
||||
default: null,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['news.created', 'news.updated', 'news.deleted', 'news.scheduled', 'news.published'],
|
||||
required: [true, 'Тип уведомления обязателен'],
|
||||
},
|
||||
news: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'News',
|
||||
default: null,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
required: [true, 'Заголовок уведомления обязателен'],
|
||||
trim: true,
|
||||
},
|
||||
message: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
isRead: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: { createdAt: true, updatedAt: false },
|
||||
},
|
||||
);
|
||||
|
||||
// Индекс для быстрого поиска непрочитанных
|
||||
notificationSchema.index({ user: 1, isRead: 1, createdAt: -1 });
|
||||
|
||||
const Notification = model<INotification>('Notification', notificationSchema);
|
||||
|
||||
export default Notification;
|
||||
@@ -1,24 +1,35 @@
|
||||
import { compare, hash } from 'bcrypt';
|
||||
import mongoose from 'mongoose';
|
||||
import mongoose, { type HydratedDocument } from 'mongoose';
|
||||
|
||||
import { signUserToken, verifyUserToken } from '../utils/jwt.js';
|
||||
/**
|
||||
* Интерфейс документа пользователя.
|
||||
*/
|
||||
export interface IUser {
|
||||
email: string;
|
||||
passwordHash: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
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 не дублирует её.
|
||||
*/
|
||||
export const userSchema = new mongoose.Schema(
|
||||
const userSchema = new mongoose.Schema<IUser>(
|
||||
{
|
||||
email: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
lowercase: true,
|
||||
trim: true,
|
||||
index: true,
|
||||
},
|
||||
passwordHash: {
|
||||
type: String,
|
||||
@@ -36,7 +47,7 @@ export const userSchema = new mongoose.Schema(
|
||||
* Хранит email и bcrypt-хеш пароля. Пароль никогда не возвращается
|
||||
* в ответах API — только через select('-passwordHash') или omit.
|
||||
*/
|
||||
export const User = mongoose.model('User', userSchema);
|
||||
export const User = mongoose.model<IUser>('User', userSchema);
|
||||
|
||||
/**
|
||||
* Хешит пароль с bcrypt (cost 12).
|
||||
@@ -58,9 +69,3 @@ export async function hashPassword(password: string): Promise<string> {
|
||||
export async function comparePassword(password: string, hashValue: string): Promise<boolean> {
|
||||
return compare(password, hashValue);
|
||||
}
|
||||
|
||||
// Реэкспорт JWT-утилит для удобства импорта
|
||||
export { signUserToken, verifyUserToken };
|
||||
export type { JwtPayload } from '../utils/jwt.js';
|
||||
|
||||
|
||||
|
||||
@@ -6,38 +6,97 @@ 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 VALIDATION_MSG = 'Некорректный email или пароль';
|
||||
/** Сообщение об ошибке авторизации. */
|
||||
const AUTH_MSG = 'Требуется авторизация';
|
||||
|
||||
/**
|
||||
* Извлекает email и password из тела запроса.
|
||||
* Проверяет 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} если email или password некорректны
|
||||
* @throws {ApiError} с конкретным сообщением о проблеме
|
||||
*/
|
||||
function extractCredentials(rawBody: unknown): { email: string; password: string } {
|
||||
if (typeof rawBody !== 'object' || rawBody === null) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', VALIDATION_MSG);
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Тело запроса некорректно');
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
|
||||
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 || !emailStr.includes('@')) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', VALIDATION_MSG);
|
||||
if (emailStr.length === 0) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Email не указан');
|
||||
}
|
||||
if (!isValidEmail(emailStr)) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', `Некорректный формат email: ${emailStr}`);
|
||||
}
|
||||
if (passwordStr.length === 0) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', 'Пароль не указан');
|
||||
}
|
||||
if (passwordStr.length < 8) {
|
||||
throw new ApiError(400, 'VALIDATION_ERROR', VALIDATION_MSG);
|
||||
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 },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,24 +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 });
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- user.id из mongoose
|
||||
const token = signUserToken(user.id);
|
||||
|
||||
res.status(201).json({
|
||||
token,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
|
||||
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;
|
||||
}
|
||||
@@ -101,11 +143,9 @@ authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- user.id из mongoose
|
||||
const token = signUserToken(user.id);
|
||||
res.json({
|
||||
token,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
|
||||
user: { id: user.id, email: user.email },
|
||||
});
|
||||
}));
|
||||
@@ -114,23 +154,21 @@ 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.headers['x-user-id'] установлен 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;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- mongoose документ
|
||||
res.json({ id: user.id, email: user.email });
|
||||
}));
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import { Router } from 'express';
|
||||
|
||||
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 из URL (req.params.id всегда строка в Express). */
|
||||
function paramsId(req: Request): string {
|
||||
const raw = req.params.id;
|
||||
return Array.isArray(raw) ? raw[0] ?? '' : raw;
|
||||
}
|
||||
|
||||
/** Безопасно извлекает поле из req.body. */
|
||||
function bodyField(req: Request, key: string): unknown {
|
||||
const raw = (req.body ?? {}) as Record<string, unknown>;
|
||||
return raw[key];
|
||||
}
|
||||
|
||||
/** Форматирует документ новости для JSON. */
|
||||
function serializeNews(n: InstanceType<typeof News>) {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает 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 серверу.
|
||||
*
|
||||
* @param io — Socket.IO server для отправки real-time событий
|
||||
* @returns настроенный Router
|
||||
*/
|
||||
export function createNewsRouter(io?: SocketIOServer): Router {
|
||||
const router = Router();
|
||||
router.use(requireAuth);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Дефолтный экспорт (без Socket.IO). */
|
||||
const newsRouter = createNewsRouter();
|
||||
export default newsRouter;
|
||||
@@ -0,0 +1,132 @@
|
||||
import { Router } from 'express';
|
||||
|
||||
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 авторизованного пользователя или бросает 401.
|
||||
*
|
||||
* @param req — запрос Express
|
||||
* @returns id пользователя
|
||||
*/
|
||||
function getUserId(req: Request): string {
|
||||
const userId = req.user?.id;
|
||||
if (userId === undefined) {
|
||||
throw new ApiError(401, 'UNAUTHORIZED', AUTH_MSG);
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирует документ уведомления для JSON.
|
||||
*
|
||||
* @param n — документ Mongoose
|
||||
* @returns объект с публичными полями
|
||||
*/
|
||||
function serializeNotification(n: InstanceType<typeof Notification>) {
|
||||
return {
|
||||
id: n._id,
|
||||
actor: n.actor,
|
||||
type: n.type,
|
||||
news: n.news,
|
||||
title: n.title,
|
||||
message: n.message,
|
||||
isRead: n.isRead,
|
||||
createdAt: n.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/notifications
|
||||
* Список уведомлений текущего пользователя (последние 50).
|
||||
*
|
||||
* @returns 200 { notifications: [...] }
|
||||
*/
|
||||
notificationRouter.get(
|
||||
'/',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const items = await Notification.find({ user: userId })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(50);
|
||||
|
||||
res.json({ notifications: items.map(serializeNotification) });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/notifications/unread-count
|
||||
* Количество непрочитанных уведомлений.
|
||||
*
|
||||
* @returns 200 { count: number }
|
||||
*/
|
||||
notificationRouter.get(
|
||||
'/unread-count',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const count = await Notification.countDocuments({ user: userId, isRead: false });
|
||||
|
||||
res.json({ count });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* PATCH /api/notifications/:id/read
|
||||
* Помечает одно уведомление как прочитанное.
|
||||
*
|
||||
* @returns 200 { notification: { ... } }
|
||||
*/
|
||||
notificationRouter.patch(
|
||||
'/:id/read',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const notification = await Notification.findOne({ _id: paramsId(req), user: userId });
|
||||
if (notification === null) {
|
||||
throw new ApiError(404, 'NOTIFICATION_NOT_FOUND', 'Уведомление не найдено');
|
||||
}
|
||||
|
||||
notification.isRead = true;
|
||||
await notification.save();
|
||||
|
||||
res.json({ notification: serializeNotification(notification) });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/notifications/read-all
|
||||
* Помечает все уведомления как прочитанные.
|
||||
*
|
||||
* @returns 200 { count: number } — количество помеченных
|
||||
*/
|
||||
notificationRouter.post(
|
||||
'/read-all',
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = getUserId(req);
|
||||
const result = await Notification.updateMany(
|
||||
{ user: userId, isRead: false },
|
||||
{ $set: { isRead: true } },
|
||||
);
|
||||
|
||||
res.json({ count: result.modifiedCount });
|
||||
}),
|
||||
);
|
||||
|
||||
export default notificationRouter;
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Router } from 'express';
|
||||
|
||||
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 => {
|
||||
upload.single(fileFilter)(req, res, (err: unknown) => {
|
||||
if (err instanceof ApiError) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
if (err !== null && err !== undefined) {
|
||||
// MulterError или ошибка fileFilter
|
||||
const message = err instanceof Error ? err.message : 'Ошибка загрузки';
|
||||
const isFileSize = message.includes('File too large');
|
||||
next(new ApiError(isFileSize ? 413 : 400, 'UPLOAD_ERROR', message));
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/uploads
|
||||
* Загрузка одного файла. Требует авторизацию.
|
||||
*
|
||||
* @returns 201 { file: { name, url } }
|
||||
* - name: имя файла на диске (UUID.ext)
|
||||
* - url: путь для доступа /uploads/<name>
|
||||
*/
|
||||
uploadRouter.post(
|
||||
'/',
|
||||
requireAuth,
|
||||
multerHandler('file'),
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const userId = req.user?.id;
|
||||
if (userId === undefined) {
|
||||
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
|
||||
}
|
||||
|
||||
// Multer устанавливает req.file при успешной загрузке
|
||||
if (req.file === undefined) {
|
||||
throw new ApiError(400, 'NO_FILE', 'Файл не был загружен');
|
||||
}
|
||||
|
||||
const fileName = req.file.filename;
|
||||
|
||||
res.status(201).json({
|
||||
file: {
|
||||
name: fileName,
|
||||
url: `/uploads/${fileName}`,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export default uploadRouter;
|
||||
+49
-4
@@ -1,32 +1,67 @@
|
||||
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();
|
||||
|
||||
mongoose.connection.close()
|
||||
.catch((err: unknown) => {
|
||||
console.error('Ошибка при закрытии MongoDB:', err);
|
||||
})
|
||||
.finally(() => {
|
||||
server.close(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Точка входа приложения.
|
||||
*
|
||||
* Подключает MongoDB и запускает HTTP-сервер на порту из env.
|
||||
* Подключает MongoDB, создаёт HTTP-сервер, Socket.IO и Express, запускает scheduler.
|
||||
* Socket.IO подключается к HTTP-серверу через engine.io (перехватывает /socket.io).
|
||||
*/
|
||||
async function main(): Promise<void> {
|
||||
await connectDatabase();
|
||||
|
||||
const app = createApp();
|
||||
const server = http.createServer(app);
|
||||
// Создаём HTTP-сервер (без handler — добавим через server.on)
|
||||
const server = http.createServer();
|
||||
|
||||
// Socket.IO подключается к HTTP-серверу (engine.io перехватывает /socket.io)
|
||||
const io = createSocketServer(server);
|
||||
|
||||
// Express-приложение (с io для news routes и scheduler)
|
||||
const app = createApp({ io });
|
||||
server.on('request', app);
|
||||
|
||||
// Запускаем планировщик отложенной публикации (с io для real-time уведомлений)
|
||||
startPublicationScheduler(env.schedulerIntervalMs, io);
|
||||
|
||||
server.listen(env.port, () => {
|
||||
console.warn(`News Editor API запущен на порту ${String(env.port)} (${env.nodeEnv})`);
|
||||
@@ -39,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) => {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import Notification from '../models/notification.model.js';
|
||||
|
||||
import type { NotificationType } from '../models/notification.model.js';
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/** Параметры для создания уведомления. */
|
||||
interface CreateNotificationParams {
|
||||
/** Пользователь-получатель (ObjectId). */
|
||||
user: string;
|
||||
/** Пользователь-инициатор действия (ObjectId, может совпадать с user). */
|
||||
actor: string;
|
||||
/** Тип события. */
|
||||
type: NotificationType;
|
||||
/** Id новости (если применимо). */
|
||||
newsId?: string;
|
||||
/** Заголовок. */
|
||||
title: string;
|
||||
/** Сообщение. */
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохраняет уведомление в БД и отправляет real-time событие через Socket.IO.
|
||||
*
|
||||
* @param io — экземпляр Socket.IO server
|
||||
* @param params — данные уведомления (user/actor — ObjectId-строки,
|
||||
* Mongoose кастит их в ObjectId)
|
||||
*/
|
||||
export async function createNotification(
|
||||
io: SocketIOServer,
|
||||
params: CreateNotificationParams,
|
||||
): Promise<void> {
|
||||
// Mongoose кастит string → ObjectId (user/actor/newsId)
|
||||
const notification = await Notification.create({
|
||||
user: params.user,
|
||||
actor: params.actor,
|
||||
type: params.type,
|
||||
news: params.newsId ?? null,
|
||||
title: params.title,
|
||||
message: params.message,
|
||||
isRead: false,
|
||||
});
|
||||
|
||||
// Отправляем real-time событие в room получателя
|
||||
io.to(`user:${params.user}`).emit('notification', {
|
||||
id: notification._id,
|
||||
type: notification.type,
|
||||
news: notification.news,
|
||||
title: notification.title,
|
||||
message: notification.message,
|
||||
isRead: false,
|
||||
createdAt: notification.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Публикует событие в room пользователя (без сохранения в БД).
|
||||
*
|
||||
* Используется для событий, которые не являются "уведомлениями"
|
||||
* в классическом смысле (например, обновление списка в реальном времени).
|
||||
*
|
||||
* @param io — экземпляр Socket.IO server
|
||||
* @param userId — получатель
|
||||
* @param event — название события
|
||||
* @param data — payload
|
||||
*/
|
||||
export function emitToUser(
|
||||
io: SocketIOServer,
|
||||
userId: string,
|
||||
event: string,
|
||||
data: unknown,
|
||||
): void {
|
||||
io.to(`user:${userId}`).emit(event, data);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import News from '../models/news.model.js';
|
||||
|
||||
import { createNotification } from './notification.service.js';
|
||||
|
||||
import type { Server as SocketIOServer } from 'socket.io';
|
||||
|
||||
/**
|
||||
* Публикационный планировщик (MongoDB-backed poll).
|
||||
*
|
||||
* Каждые `intervalMs` миллисекунд выполняет атомарный запрос:
|
||||
* находит все новости со status='scheduled' и scheduledAt <= now,
|
||||
* атомарно переключает их в status='published'.
|
||||
*
|
||||
* Не использует 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 = DEFAULT_INTERVAL_MS,
|
||||
io?: SocketIOServer,
|
||||
): void {
|
||||
if (timer) {
|
||||
return;
|
||||
}
|
||||
if (io !== undefined) {
|
||||
ioRef = io;
|
||||
}
|
||||
currentIntervalMs = intervalMs;
|
||||
|
||||
const poll = async (): Promise<void> => {
|
||||
try {
|
||||
const now = new Date();
|
||||
|
||||
// Атомарный update: только scheduled → published, если scheduledAt уже прошёл
|
||||
const result = await News.updateMany(
|
||||
{ status: 'scheduled', scheduledAt: { $lte: now } },
|
||||
{ $set: { status: 'published', publishedAt: now, scheduledAt: null } },
|
||||
);
|
||||
|
||||
if (result.modifiedCount > 0) {
|
||||
console.log(`[scheduler] Опубликовано новостей: ${String(result.modifiedCount)}`);
|
||||
// Уведомляем авторов об автоматической публикации
|
||||
await notifyPublishedAuthors(now);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[scheduler] Ошибка при публикации:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// Первый poll сразу
|
||||
poll().catch(() => {
|
||||
// ошибки логируются внутри poll
|
||||
});
|
||||
timer = setInterval(() => {
|
||||
poll().catch(() => {
|
||||
// ошибки логируются внутри poll
|
||||
});
|
||||
}, intervalMs);
|
||||
|
||||
// Не держать процесс живым только ради scheduler
|
||||
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).
|
||||
*/
|
||||
export function stopPublicationScheduler(): void {
|
||||
if (timer) {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
ioRef = null;
|
||||
}
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Расширение типов Socket.IO для хранения userId в socket.data.
|
||||
*/
|
||||
import type { Socket } from 'socket.io';
|
||||
|
||||
declare module 'socket.io' {
|
||||
interface Socket {
|
||||
/** Id авторизованного пользователя (устанавливается middleware). */
|
||||
userId: string;
|
||||
}
|
||||
}
|
||||
|
||||
export type { Socket };
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Server } from 'socket.io';
|
||||
|
||||
import { env } from '../config/env.js';
|
||||
import { verifyUserToken } from '../utils/jwt.js';
|
||||
|
||||
import type { Server as HttpServer } from 'node:http';
|
||||
import type { Server as IOServer } from 'socket.io';
|
||||
|
||||
/**
|
||||
* Создаёт и настраивает Socket.IO сервер.
|
||||
*
|
||||
* @param httpServer — HTTP-сервер Express
|
||||
* @returns настроенный Socket.IO server
|
||||
*/
|
||||
export function createSocketServer(httpServer: HttpServer): IOServer {
|
||||
const io = new Server(httpServer, {
|
||||
cors: { origin: env.clientOrigins },
|
||||
});
|
||||
|
||||
// Middleware аутентификации: проверяем JWT из handshake.auth.token
|
||||
io.use((socket, next) => {
|
||||
// handshake.auth — any в типах socket.io, извлекаем token
|
||||
const token: unknown = socket.handshake.auth.token;
|
||||
|
||||
if (typeof token !== 'string' || token.length === 0) {
|
||||
next(new Error('UNAUTHORIZED: отсутствует токен'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const payload = verifyUserToken(token);
|
||||
socket.userId = payload.id;
|
||||
next();
|
||||
} catch {
|
||||
next(new Error('UNAUTHORIZED: недействительный токен'));
|
||||
}
|
||||
});
|
||||
|
||||
// При подключении — добавляем socket в room пользователя
|
||||
io.on('connection', (socket) => {
|
||||
void socket.join(`user:${socket.userId}`);
|
||||
});
|
||||
|
||||
return io;
|
||||
}
|
||||
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 {};
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Ошибочный статус HTTP-ответа (подмножество используемых кодов).
|
||||
*/
|
||||
export type ApiErrorCode = 400 | 401 | 403 | 404 | 409 | 500;
|
||||
export type ApiErrorCode = 400 | 401 | 403 | 404 | 409 | 413 | 500;
|
||||
|
||||
/**
|
||||
* Ожидаемая (предусмотренная) ошибка приложения.
|
||||
|
||||
+11
-20
@@ -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,10 +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 };
|
||||
// eslint-disable-next-line import-x/no-named-as-default-member -- jsonwebtoken использует default export
|
||||
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 : '';
|
||||
}
|
||||
|
||||
@@ -35,9 +27,8 @@ export function signUserToken(userId: string): string {
|
||||
* @param token — токен (без префикса Bearer)
|
||||
* @returns payload токена
|
||||
*/
|
||||
export function verifyUserToken(token: string): JwtPayload {
|
||||
// eslint-disable-next-line import-x/no-named-as-default-member -- jsonwebtoken использует default export
|
||||
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');
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ function fieldOf(obj: unknown, key: string): string | undefined {
|
||||
if (typeof obj !== 'object' || obj === null) {
|
||||
return undefined;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
|
||||
const record = obj as Record<string, unknown>;
|
||||
const value = record[key];
|
||||
return typeof value === 'string' ? value : undefined;
|
||||
@@ -48,7 +47,6 @@ function userEmailOf(body: unknown): string | undefined {
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return undefined;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
|
||||
const record = body as Record<string, unknown>;
|
||||
// /me возвращает { id, email } на верхнем уровне, register/login — { user: { id, email } }
|
||||
if (record.email !== undefined) {
|
||||
@@ -67,7 +65,6 @@ function userIdOf(body: unknown): string | undefined {
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return undefined;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- извлечение полей из unknown
|
||||
const user = (body as Record<string, unknown>).user;
|
||||
return fieldOf(user, 'id');
|
||||
}
|
||||
@@ -182,7 +179,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)
|
||||
|
||||
@@ -16,12 +16,10 @@ function errorCodeOf(body: unknown): string | undefined {
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return undefined;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- извлечение полей из unknown
|
||||
const error = (body as { error?: unknown }).error;
|
||||
if (typeof error !== 'object' || error === null) {
|
||||
return undefined;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- извлечение полей из unknown
|
||||
const code = (error as { code?: unknown }).code;
|
||||
return typeof code === 'string' ? code : undefined;
|
||||
}
|
||||
@@ -68,7 +66,7 @@ describe('API skeleton', () => {
|
||||
|
||||
describe('error middleware', () => {
|
||||
it('обрабатывает ApiError с её статусом и кодом', async () => {
|
||||
const errorApp = createApp(throwingMiddleware('/api/test-conflict', new ApiError(409, 'CONFLICT', 'Тестовый конфликт')));
|
||||
const errorApp = createApp({ extraMiddleware: throwingMiddleware('/api/test-conflict', new ApiError(409, 'CONFLICT', 'Тестовый конфликт')) });
|
||||
const res = await request(errorApp).get('/api/test-conflict');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
@@ -76,7 +74,7 @@ describe('API skeleton', () => {
|
||||
});
|
||||
|
||||
it('возвращает 500 для непредвиденных ошибок', async () => {
|
||||
const errorApp = createApp(throwingMiddleware('/api/test-unexpected', new Error('Внутренний сбой')));
|
||||
const errorApp = createApp({ extraMiddleware: throwingMiddleware('/api/test-unexpected', new Error('Внутренний сбой')) });
|
||||
const res = await request(errorApp).get('/api/test-unexpected');
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import request from 'supertest';
|
||||
import { describe, expect, it, beforeAll, afterAll } from 'vitest';
|
||||
|
||||
import { createApp } from '../src/app.js';
|
||||
import News from '../src/models/news.model.js';
|
||||
import { User, hashPassword } from '../src/models/user.model.js';
|
||||
import { startPublicationScheduler, stopPublicationScheduler } from '../src/services/publicationScheduler.service.js';
|
||||
import { signUserToken } from '../src/utils/jwt.js';
|
||||
|
||||
const app = createApp();
|
||||
const TEST_EMAIL = 'publish-test@example.com';
|
||||
|
||||
let authToken = '';
|
||||
|
||||
beforeAll(async () => {
|
||||
const user = await User.create({
|
||||
email: TEST_EMAIL,
|
||||
passwordHash: await hashPassword('Test-Pass-123'),
|
||||
});
|
||||
authToken = signUserToken(user.id);
|
||||
});
|
||||
|
||||
function authed(req: request.Test): request.Test {
|
||||
return req.set('Authorization', `Bearer ${authToken}`);
|
||||
}
|
||||
|
||||
/** Создаёт тестовую новость и возвращает её id. */
|
||||
async function createTestNews(title: string): Promise<string> {
|
||||
const res = await authed(request(app).post('/api/news').send({ title, content: 'Тест' }));
|
||||
return res.body.news.id;
|
||||
}
|
||||
|
||||
describe('Публикация новостей', () => {
|
||||
describe('POST /api/news/:id/publish', () => {
|
||||
it('публикует draft-новость', async () => {
|
||||
const id = await createTestNews('К публикации');
|
||||
const res = await authed(request(app).post(`/api/news/${id}/publish`));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.news.status).toBe('published');
|
||||
expect(res.body.news.publishedAt).not.toBeNull();
|
||||
});
|
||||
|
||||
it('повторная публикация возвращает 400', async () => {
|
||||
const id = await createTestNews('Уже опубликована');
|
||||
await authed(request(app).post(`/api/news/${id}/publish`));
|
||||
const res = await authed(request(app).post(`/api/news/${id}/publish`));
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('ALREADY_PUBLISHED');
|
||||
});
|
||||
|
||||
it('несуществующий id возвращает 404', async () => {
|
||||
const res = await authed(request(app).post('/api/news/000000000000000000000000/publish'));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('чужая новость — 404', async () => {
|
||||
const id = await createTestNews('Своя');
|
||||
const user2 = await User.create({
|
||||
email: 'publish-other@example.com',
|
||||
passwordHash: await hashPassword('Other-Pass-123'),
|
||||
});
|
||||
const token2 = signUserToken(user2.id);
|
||||
|
||||
const res = await request(app)
|
||||
.post(`/api/news/${id}/publish`)
|
||||
.set('Authorization', `Bearer ${token2}`);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/news/:id/schedule', () => {
|
||||
it('устанавливает отложенную публикацию', async () => {
|
||||
const id = await createTestNews('Отложенная');
|
||||
const futureDate = new Date(Date.now() + 3600_000).toISOString();
|
||||
|
||||
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: futureDate }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.news.status).toBe('scheduled');
|
||||
expect(res.body.news.scheduledAt).toBe(futureDate);
|
||||
});
|
||||
|
||||
it('дата в прошлом возвращает 400', async () => {
|
||||
const id = await createTestNews('Прошлая дата');
|
||||
const pastDate = new Date(Date.now() - 3600_000).toISOString();
|
||||
|
||||
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: pastDate }));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('невалидная дата возвращает 400', async () => {
|
||||
const id = await createTestNews('Невалидная дата');
|
||||
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: 'not-a-date' }));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('отсутствие scheduledAt возвращает 400', async () => {
|
||||
const id = await createTestNews('Без даты');
|
||||
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({}));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('уже опубликованная — 400', async () => {
|
||||
const id = await createTestNews('Публикация и schedule');
|
||||
await authed(request(app).post(`/api/news/${id}/publish`));
|
||||
const futureDate = new Date(Date.now() + 3600_000).toISOString();
|
||||
|
||||
const res = await authed(request(app).post(`/api/news/${id}/schedule`).send({ scheduledAt: futureDate }));
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('ALREADY_PUBLISHED');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Publication Scheduler', () => {
|
||||
afterAll(() => {
|
||||
stopPublicationScheduler();
|
||||
});
|
||||
|
||||
it('автоматически публикует scheduled новости с прошедшим scheduledAt', async () => {
|
||||
// Создаём новость и вручную ставим scheduledAt в прошлое
|
||||
const id = await createTestNews('Авто-публикация');
|
||||
const pastDate = new Date(Date.now() - 60_000);
|
||||
await News.updateOne({ _id: id }, { $set: { status: 'scheduled', scheduledAt: pastDate } });
|
||||
|
||||
// Запускаем scheduler с коротким интервалом
|
||||
startPublicationScheduler(500);
|
||||
|
||||
// Ждём до 3 секунд пока scheduler опубликует
|
||||
const deadline = Date.now() + 3000;
|
||||
let published = false;
|
||||
while (Date.now() < deadline) {
|
||||
const news = await News.findById(id);
|
||||
if (news?.status === 'published') {
|
||||
published = true;
|
||||
break;
|
||||
}
|
||||
|
||||
await new Promise<void>((r) => { setTimeout(r, 100); });
|
||||
}
|
||||
|
||||
stopPublicationScheduler();
|
||||
expect(published).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import request from 'supertest';
|
||||
import { describe, expect, it, beforeAll, afterAll } from 'vitest';
|
||||
|
||||
import { createApp } from '../src/app.js';
|
||||
import { env } from '../src/config/env.js';
|
||||
import { User, hashPassword } from '../src/models/user.model.js';
|
||||
import { signUserToken } from '../src/utils/jwt.js';
|
||||
|
||||
const app = createApp();
|
||||
const TEST_EMAIL = 'upload-test@example.com';
|
||||
|
||||
let authToken = '';
|
||||
const uploadedFiles: string[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
// Убеждаемся что uploadDir существует
|
||||
if (!fs.existsSync(env.uploadDir)) {
|
||||
fs.mkdirSync(env.uploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
const user = await User.create({
|
||||
email: TEST_EMAIL,
|
||||
passwordHash: await hashPassword('Upload-Pass-123'),
|
||||
});
|
||||
authToken = signUserToken(user.id);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
// Удаляем загруженные тестовые файлы
|
||||
for (const file of uploadedFiles) {
|
||||
const filePath = path.join(env.uploadDir, file);
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/** Запоминает файл для последующей очистки. */
|
||||
function trackFile(name: string): void {
|
||||
uploadedFiles.push(name);
|
||||
}
|
||||
|
||||
/** Создаёт маленький PNG-файл (1x1 пиксель). */
|
||||
function createTestPng(): Buffer {
|
||||
return Buffer.from(
|
||||
'89504e470d0a1a0a0000000d4948445200000001000000010802000000907753' +
|
||||
'de0000000c4944415408d763f8cfc0f0000000050001b5f73564000000004945' +
|
||||
'4e44ae426082',
|
||||
'hex',
|
||||
);
|
||||
}
|
||||
|
||||
describe('Загрузка файлов', () => {
|
||||
it('POST /api/uploads без токена — 401', async () => {
|
||||
const png = createTestPng();
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.attach('file', png, 'test.png');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('успешная загрузка PNG', async () => {
|
||||
const png = createTestPng();
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.attach('file', png, 'test.png');
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.file.name).toBeDefined();
|
||||
expect(res.body.file.url).toBe(`/uploads/${res.body.file.name}`);
|
||||
expect(res.body.file.name).toMatch(/^[0-9a-f-]{36}\.png$/);
|
||||
|
||||
trackFile(res.body.file.name);
|
||||
|
||||
// Файл существует на диске
|
||||
const filePath = path.join(env.uploadDir, res.body.file.name);
|
||||
expect(fs.existsSync(filePath)).toBe(true);
|
||||
});
|
||||
|
||||
it('загрузка PDF', async () => {
|
||||
const pdf = Buffer.from('%PDF-1.4 test');
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.attach('file', pdf, 'test.pdf');
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.file.name).toMatch(/\.pdf$/);
|
||||
trackFile(res.body.file.name);
|
||||
});
|
||||
|
||||
it('запрещённый MIME — 400', async () => {
|
||||
const exe = Buffer.from('MZ executable content');
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.attach('file', exe, 'malware.exe');
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('UPLOAD_ERROR');
|
||||
});
|
||||
|
||||
it('без файла — 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('NO_FILE');
|
||||
});
|
||||
|
||||
it('GET /uploads/<name> отдаёт файл', async () => {
|
||||
const png = createTestPng();
|
||||
const uploadRes = await request(app)
|
||||
.post('/api/uploads')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.attach('file', png, 'static-test.png');
|
||||
|
||||
const fileName = uploadRes.body.file.name;
|
||||
trackFile(fileName);
|
||||
|
||||
const res = await request(app).get(`/uploads/${fileName}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('image/png');
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,8 @@ export default defineConfig({
|
||||
setupFiles: ['tests/setup.ts'],
|
||||
globalSetup: ['tests/global-setup.ts'],
|
||||
include: ['tests/**/*.test.ts'],
|
||||
// Последовательное выполнение: scheduler влияет на общее состояние БД
|
||||
fileParallelism: false,
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
include: ['src/**/*.ts'],
|
||||
|
||||
Reference in New Issue
Block a user