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
+2
View File
@@ -5,6 +5,7 @@ import helmet from 'helmet';
import { env } from './config/env.js';
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';
/**
@@ -36,6 +37,7 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
// API-маршруты
app.use('/api', healthRouter);
app.use('/api/auth', authRouter);
// Дополнительные middleware (тестовые маршруты, заглушки)
if (extraMiddleware) {
+49
View File
@@ -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', 'Невалидный или истёкший токен'));
}
}
+66
View File
@@ -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';
+137
View File
@@ -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;
+50
View File
@@ -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 };
}