Phase 2: Auth — User model, bcrypt, register, login, JWT, middleware, интеграционные тесты

This commit is contained in:
Suslov-MD
2026-08-16 05:33:27 +00:00
parent 7d511befaa
commit 391b8dff88
10 changed files with 554 additions and 8 deletions
+196
View File
@@ -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');
});
});
});
+30
View File
@@ -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
View File
@@ -1,10 +1,25 @@
/**
* Инициализация тестового окружения.
* Инициализация тестового окружения (per test file).
*
* Задаёт переменные окружения до импорта модулей приложения
* (env.ts читает process.env при первой загрузке).
* Подключает Mongoose к mongodb-memory-server (URI установлен
* в global-setup) и очищает БД после каждого теста.
*/
process.env.NODE_ENV = 'test';
process.env.MONGODB_URI = 'mongodb://127.0.0.1:27017/newsEditorTest';
process.env.JWT_SECRET = 'test-secret';
process.env.CLIENT_ORIGIN = 'http://localhost:5173';
import mongoose from 'mongoose';
import { afterAll, beforeEach } from 'vitest';
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();
});