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
+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 };
}