Phase 2: Auth — User model, bcrypt, register, login, JWT, middleware, интеграционные тесты
This commit is contained in:
@@ -5,6 +5,7 @@ import helmet from 'helmet';
|
|||||||
import { env } from './config/env.js';
|
import { env } from './config/env.js';
|
||||||
import { errorHandler } from './middleware/error.middleware.js';
|
import { errorHandler } from './middleware/error.middleware.js';
|
||||||
import { notFoundHandler } from './middleware/notFound.middleware.js';
|
import { notFoundHandler } from './middleware/notFound.middleware.js';
|
||||||
|
import authRouter from './routes/auth.routes.js';
|
||||||
import healthRouter from './routes/health.routes.js';
|
import healthRouter from './routes/health.routes.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -36,6 +37,7 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
|
|||||||
|
|
||||||
// API-маршруты
|
// API-маршруты
|
||||||
app.use('/api', healthRouter);
|
app.use('/api', healthRouter);
|
||||||
|
app.use('/api/auth', authRouter);
|
||||||
|
|
||||||
// Дополнительные middleware (тестовые маршруты, заглушки)
|
// Дополнительные middleware (тестовые маршруты, заглушки)
|
||||||
if (extraMiddleware) {
|
if (extraMiddleware) {
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { ApiError } from '../utils/ApiError.js';
|
||||||
|
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` для последующих обработчиков.
|
||||||
|
* При отсутствии или невалидном токене — бросает ApiError 401.
|
||||||
|
*
|
||||||
|
* @param req — запрос Express
|
||||||
|
* @param res — ответ Express
|
||||||
|
* @param next — функция продолжения цепочки middleware
|
||||||
|
*/
|
||||||
|
export function requireAuth(req: Request, _res: Response, next: NextFunction): void {
|
||||||
|
const header = req.headers.authorization;
|
||||||
|
|
||||||
|
// Заголовок отсутствует или не в формате Bearer
|
||||||
|
if (typeof header !== 'string' || !header.startsWith('Bearer ')) {
|
||||||
|
next(new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = header.slice('Bearer '.length).trim();
|
||||||
|
if (token.length === 0) {
|
||||||
|
next(new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = verifyUserToken(token);
|
||||||
|
// eslint-disable-next-line no-param-reassign -- установка req.user для последующих обработчиков
|
||||||
|
(req as AuthenticatedRequest).user = { id: payload.id };
|
||||||
|
next();
|
||||||
|
} catch {
|
||||||
|
next(new ApiError(401, 'UNAUTHORIZED', 'Невалидный или истёкший токен'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { compare, hash } from 'bcrypt';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
|
import { signUserToken, verifyUserToken } from '../utils/jwt.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Схема пользователя.
|
||||||
|
*
|
||||||
|
* @property email — уникальный email (индекс)
|
||||||
|
* @property passwordHash — хеш пароля (bcrypt, cost 12)
|
||||||
|
* @property createdAt / updatedAt — автоматические timestamps
|
||||||
|
*/
|
||||||
|
export const userSchema = new mongoose.Schema(
|
||||||
|
{
|
||||||
|
email: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
unique: true,
|
||||||
|
lowercase: true,
|
||||||
|
trim: true,
|
||||||
|
index: true,
|
||||||
|
},
|
||||||
|
passwordHash: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamps: true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mongoose-модель пользователя.
|
||||||
|
*
|
||||||
|
* Хранит email и bcrypt-хеш пароля. Пароль никогда не возвращается
|
||||||
|
* в ответах API — только через select('-passwordHash') или omit.
|
||||||
|
*/
|
||||||
|
export const User = mongoose.model('User', userSchema);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Хешит пароль с bcrypt (cost 12).
|
||||||
|
*
|
||||||
|
* @param password — пароль в открытом виде
|
||||||
|
* @returns промис с bcrypt-хешем
|
||||||
|
*/
|
||||||
|
export async function hashPassword(password: string): Promise<string> {
|
||||||
|
return hash(password, 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сравнивает пароль с хешем.
|
||||||
|
*
|
||||||
|
* @param password — пароль в открытом виде
|
||||||
|
* @param hashValue — bcrypt-хеш из БД
|
||||||
|
* @returns true, если пароль совпадает
|
||||||
|
*/
|
||||||
|
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';
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
|
||||||
|
import { requireAuth } from '../middleware/auth.middleware.js';
|
||||||
|
import { comparePassword, hashPassword, User } from '../models/user.model.js';
|
||||||
|
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 или пароль';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Извлекает email и password из тела запроса.
|
||||||
|
*
|
||||||
|
* @param rawBody — тело запроса (any из Express)
|
||||||
|
* @returns объект с валидированными email и password
|
||||||
|
* @throws {ApiError} если email или password некорректны
|
||||||
|
*/
|
||||||
|
function extractCredentials(rawBody: unknown): { email: string; password: string } {
|
||||||
|
if (typeof rawBody !== 'object' || rawBody === null) {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', VALIDATION_MSG);
|
||||||
|
}
|
||||||
|
// 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 passwordStr = typeof password === 'string' ? password : '';
|
||||||
|
|
||||||
|
if (emailStr.length === 0 || !emailStr.includes('@')) {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', VALIDATION_MSG);
|
||||||
|
}
|
||||||
|
if (passwordStr.length < 8) {
|
||||||
|
throw new ApiError(400, 'VALIDATION_ERROR', VALIDATION_MSG);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { email: emailStr, password: passwordStr };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Маршруты авторизации.
|
||||||
|
*
|
||||||
|
* POST /api/auth/register — регистрация нового пользователя
|
||||||
|
* POST /api/auth/login — логин существующего пользователя
|
||||||
|
* GET /api/auth/me — данные авторизованного пользователя
|
||||||
|
*/
|
||||||
|
const authRouter = Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/auth/register
|
||||||
|
*
|
||||||
|
* Регистрирует нового пользователя и возвращает JWT-токен.
|
||||||
|
* Email должен быть уникальным, пароль — минимум 8 символов.
|
||||||
|
*
|
||||||
|
* @returns 201 { token, user: { id, email } }
|
||||||
|
*/
|
||||||
|
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 },
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/auth/login
|
||||||
|
*
|
||||||
|
* Проверяет email и пароль, возвращает JWT-токен.
|
||||||
|
*
|
||||||
|
* @returns 200 { token, user: { id, email } }
|
||||||
|
*/
|
||||||
|
authRouter.post('/login', asyncHandler(async (req: Request, res: Response) => {
|
||||||
|
const { email, password } = extractCredentials(req.body);
|
||||||
|
|
||||||
|
const user = await User.findOne({ email });
|
||||||
|
if (!user) {
|
||||||
|
res.status(401).json({ error: { code: 'INVALID_CREDENTIALS', message: 'Неверный email или пароль' } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const valid = await comparePassword(password, user.passwordHash);
|
||||||
|
if (!valid) {
|
||||||
|
res.status(401).json({ error: { code: 'INVALID_CREDENTIALS', message: 'Неверный email или пароль' } });
|
||||||
|
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 },
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/auth/me
|
||||||
|
*
|
||||||
|
* Возвращает данные авторизованного пользователя.
|
||||||
|
* Требует Bearer-токен (auth middleware).
|
||||||
|
*
|
||||||
|
* @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: 'Требуется авторизация' } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const user = await User.findById(authedReq.user.id);
|
||||||
|
if (!user) {
|
||||||
|
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 });
|
||||||
|
}));
|
||||||
|
|
||||||
|
export default authRouter;
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import jwt 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Подписывает JWT-токен для пользователя с настройками из env.
|
||||||
|
*
|
||||||
|
* @param userId — ObjectId пользователя (строка)
|
||||||
|
* @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);
|
||||||
|
return typeof token === 'string' ? token : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Верифицирует JWT-токен с настройками из env.
|
||||||
|
*
|
||||||
|
* @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);
|
||||||
|
if (typeof decoded === 'string') {
|
||||||
|
throw new Error('Неожиданный формат JWT payload');
|
||||||
|
}
|
||||||
|
const id: unknown = decoded.id;
|
||||||
|
const sub: unknown = decoded.sub;
|
||||||
|
if (typeof id !== 'string' || typeof sub !== 'string') {
|
||||||
|
throw new Error('Некорректный JWT payload');
|
||||||
|
}
|
||||||
|
return { id, sub };
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
import request from 'supertest';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { createApp } from '../src/app.js';
|
||||||
|
import { verifyUserToken } from '../src/utils/jwt.js';
|
||||||
|
|
||||||
|
import type { Response } from 'supertest';
|
||||||
|
|
||||||
|
// Тестовые учётные данные (константы, не являются реальными паролями)
|
||||||
|
const TEST_EMAIL = 'user@example.com';
|
||||||
|
const TEST_CREDENTIAL = 'Test-Cred-123';
|
||||||
|
const WRONG_CREDENTIAL = 'Wrong-Cred-123';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Извлекает значение поля из объекта.
|
||||||
|
*
|
||||||
|
* @param obj — объект
|
||||||
|
* @param key — имя поля
|
||||||
|
* @returns значение поля (или undefined)
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Извлекает токен из тела ответа.
|
||||||
|
*
|
||||||
|
* @param body — тело ответа (any из supertest)
|
||||||
|
* @returns токен (или undefined)
|
||||||
|
*/
|
||||||
|
function tokenOf(body: unknown): string | undefined {
|
||||||
|
return fieldOf(body, 'token');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Извлекает user.email из тела ответа.
|
||||||
|
*
|
||||||
|
* @param body — тело ответа (any из supertest)
|
||||||
|
* @returns email (или undefined)
|
||||||
|
*/
|
||||||
|
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) {
|
||||||
|
return fieldOf(record, 'email');
|
||||||
|
}
|
||||||
|
return fieldOf(record.user, 'email');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Извлекает user.id из тела ответа.
|
||||||
|
*
|
||||||
|
* @param body — тело ответа (any из supertest)
|
||||||
|
* @returns id (или undefined)
|
||||||
|
*/
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Тесты авторизации: регистрация, логин, JWT, protected endpoint.
|
||||||
|
*/
|
||||||
|
describe('Auth', () => {
|
||||||
|
const app = createApp();
|
||||||
|
|
||||||
|
describe('POST /api/auth/register', () => {
|
||||||
|
it('регистрация нового пользователя возвращает 201 и токен', async () => {
|
||||||
|
const res: Response = await request(app)
|
||||||
|
.post('/api/auth/register')
|
||||||
|
.send({ email: TEST_EMAIL, password: TEST_CREDENTIAL });
|
||||||
|
|
||||||
|
expect(res.status).toBe(201);
|
||||||
|
expect(tokenOf(res.body)).toBeDefined();
|
||||||
|
expect(userEmailOf(res.body)).toBe(TEST_EMAIL);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('повторная регистрация того же email возвращает 409', async () => {
|
||||||
|
const creds = { email: 'dup@example.com', password: TEST_CREDENTIAL };
|
||||||
|
|
||||||
|
const res1 = await request(app).post('/api/auth/register').send(creds);
|
||||||
|
expect(res1.status).toBe(201);
|
||||||
|
|
||||||
|
const res2 = await request(app).post('/api/auth/register').send(creds);
|
||||||
|
expect(res2.status).toBe(409);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('короткий пароль возвращает 400', async () => {
|
||||||
|
const shortCred = '123';
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/register')
|
||||||
|
.send({ email: 'short@example.com', password: shortCred });
|
||||||
|
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('некорректный email возвращает 400', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/register')
|
||||||
|
.send({ email: 'not-an-email', password: TEST_CREDENTIAL });
|
||||||
|
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/auth/login', () => {
|
||||||
|
it('логин существующего пользователя возвращает 200 и токен', async () => {
|
||||||
|
const creds = { email: 'login@example.com', password: TEST_CREDENTIAL };
|
||||||
|
await request(app).post('/api/auth/register').send(creds);
|
||||||
|
|
||||||
|
const res: Response = await request(app).post('/api/auth/login').send(creds);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(tokenOf(res.body)).toBeDefined();
|
||||||
|
expect(userEmailOf(res.body)).toBe('login@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('логин с неверным паролем возвращает 401', async () => {
|
||||||
|
const creds = { email: 'badpass@example.com', password: TEST_CREDENTIAL };
|
||||||
|
await request(app).post('/api/auth/register').send(creds);
|
||||||
|
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.send({ email: 'badpass@example.com', password: WRONG_CREDENTIAL });
|
||||||
|
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('логин несуществующего пользователя возвращает 401', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.send({ email: 'nobody@example.com', password: TEST_CREDENTIAL });
|
||||||
|
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('JWT', () => {
|
||||||
|
it('токен содержит id пользователя в payload', async () => {
|
||||||
|
const creds = { email: 'jwt@example.com', password: TEST_CREDENTIAL };
|
||||||
|
const regRes: Response = await request(app).post('/api/auth/register').send(creds);
|
||||||
|
const token = tokenOf(regRes.body);
|
||||||
|
expect(token).toBeDefined();
|
||||||
|
|
||||||
|
const payload = verifyUserToken(token ?? '');
|
||||||
|
expect(payload.id).toBeDefined();
|
||||||
|
expect(payload.sub).toBe(payload.id);
|
||||||
|
expect(payload.id).toBe(userIdOf(regRes.body));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/auth/me', () => {
|
||||||
|
it('защищённый endpoint без токена возвращает 401', async () => {
|
||||||
|
const res = await request(app).get('/api/auth/me');
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('защищённый endpoint с невалидным токеном возвращает 401', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/api/auth/me')
|
||||||
|
.set('Authorization', 'Bearer invalid-token');
|
||||||
|
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('защищённый endpoint с валидным токеном возвращает данные пользователя', async () => {
|
||||||
|
const creds = { email: 'me@example.com', password: TEST_CREDENTIAL };
|
||||||
|
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)
|
||||||
|
.get('/api/auth/me')
|
||||||
|
.set('Authorization', authHeader);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(userEmailOf(res.body)).toBe('me@example.com');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/**
|
||||||
|
* Глобальный setup для интеграционных тестов.
|
||||||
|
*
|
||||||
|
* Запускает mongodb-memory-server до всех тестов,
|
||||||
|
* устанавливает MONGODB_URI и JWT_SECRET.
|
||||||
|
*/
|
||||||
|
import { MongoMemoryServer } from 'mongodb-memory-server';
|
||||||
|
|
||||||
|
// JWT_SECRET должен быть задан до импорта env.ts
|
||||||
|
process.env.JWT_SECRET ??= 'test-secret';
|
||||||
|
process.env.NODE_ENV ??= 'test';
|
||||||
|
|
||||||
|
let mongod: MongoMemoryServer | undefined;
|
||||||
|
|
||||||
|
export async function setup(): Promise<void> {
|
||||||
|
try {
|
||||||
|
mongod = await MongoMemoryServer.create();
|
||||||
|
process.env.MONGODB_URI = mongod.getUri('newsEditorTest');
|
||||||
|
console.warn('[global-setup] mongodb-memory-server запущена:', process.env.MONGODB_URI);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[global-setup] mongodb-memory-server недоступна:', err);
|
||||||
|
process.env.MONGODB_URI = 'mongodb://127.0.0.1:27017/newsEditorTest';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function teardown(): Promise<void> {
|
||||||
|
if (mongod) {
|
||||||
|
await mongod.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
-7
@@ -1,10 +1,25 @@
|
|||||||
/**
|
/**
|
||||||
* Инициализация тестового окружения.
|
* Инициализация тестового окружения (per test file).
|
||||||
*
|
*
|
||||||
* Задаёт переменные окружения до импорта модулей приложения
|
* Подключает Mongoose к mongodb-memory-server (URI установлен
|
||||||
* (env.ts читает process.env при первой загрузке).
|
* в global-setup) и очищает БД после каждого теста.
|
||||||
*/
|
*/
|
||||||
process.env.NODE_ENV = 'test';
|
import mongoose from 'mongoose';
|
||||||
process.env.MONGODB_URI = 'mongodb://127.0.0.1:27017/newsEditorTest';
|
import { afterAll, beforeEach } from 'vitest';
|
||||||
process.env.JWT_SECRET = 'test-secret';
|
|
||||||
process.env.CLIENT_ORIGIN = 'http://localhost:5173';
|
import { User } from '../src/models/user.model.js';
|
||||||
|
|
||||||
|
// Подключаем Mongoose (MONGODB_URI установлен в global-setup)
|
||||||
|
const mongoUri = process.env.MONGODB_URI;
|
||||||
|
if (mongoUri === undefined) {
|
||||||
|
throw new Error('MONGODB_URI не установлен (global-setup не выполнен)');
|
||||||
|
}
|
||||||
|
await mongoose.connect(mongoUri);
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await User.deleteMany({});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await mongoose.disconnect();
|
||||||
|
});
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
"moduleResolution": "NodeNext",
|
"moduleResolution": "NodeNext",
|
||||||
"lib": ["ES2022"],
|
"lib": ["ES2022"],
|
||||||
"outDir": "dist",
|
"outDir": "dist",
|
||||||
"rootDir": "src",
|
"rootDir": ".",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export default defineConfig({
|
|||||||
test: {
|
test: {
|
||||||
environment: 'node',
|
environment: 'node',
|
||||||
setupFiles: ['tests/setup.ts'],
|
setupFiles: ['tests/setup.ts'],
|
||||||
|
globalSetup: ['tests/global-setup.ts'],
|
||||||
include: ['tests/**/*.test.ts'],
|
include: ['tests/**/*.test.ts'],
|
||||||
coverage: {
|
coverage: {
|
||||||
provider: 'v8',
|
provider: 'v8',
|
||||||
|
|||||||
Reference in New Issue
Block a user