initial commit

This commit is contained in:
2026-06-09 14:07:37 +03:30
parent 30ac533800
commit 996a4fcda7
121 changed files with 20557 additions and 3 deletions
+69
View File
@@ -0,0 +1,69 @@
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { Request } from 'express';
import { AuthService } from './auth.service';
import { CurrentUser } from './decorators/current-user.decorator';
import { LoginDto } from './dto/login.dto';
import { RefreshTokenDto } from './dto/refresh-token.dto';
import { AuthTokensDto } from './dto/auth-tokens.dto';
import { ProfileDto } from './dto/profile.dto';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { AuthenticatedUser } from './interfaces/authenticated-user.interface';
@ApiTags('Auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('login')
@ApiOperation({ summary: 'Login with username and password' })
@ApiResponse({ status: 200, type: AuthTokensDto })
@ApiResponse({ status: 401, description: 'Invalid credentials' })
@ApiResponse({ status: 403, description: 'Inactive or blocked account' })
async login(@Body() dto: LoginDto, @Req() req: Request): Promise<AuthTokensDto> {
return this.authService.login(dto, {
ip: req.ip,
userAgent: req.headers['user-agent'],
});
}
@Post('refresh')
@ApiOperation({ summary: 'Refresh access token' })
@ApiResponse({ status: 200, type: AuthTokensDto })
async refresh(@Body() dto: RefreshTokenDto, @Req() req: Request): Promise<AuthTokensDto> {
return this.authService.refresh(dto.refreshToken, {
ip: req.ip,
userAgent: req.headers['user-agent'],
});
}
@Post('logout')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: 'Logout and invalidate refresh token' })
@ApiResponse({ status: 200, description: 'Logged out successfully' })
async logout(
@CurrentUser() user: AuthenticatedUser,
@Req() req: Request,
): Promise<{ message: string }> {
await this.authService.logout(user.id, {
ip: req.ip,
userAgent: req.headers['user-agent'],
});
return { message: 'Logged out successfully' };
}
@Get('profile')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: 'Get current user profile' })
@ApiResponse({ status: 200, type: ProfileDto })
async profile(@CurrentUser() user: AuthenticatedUser): Promise<ProfileDto> {
return this.authService.getProfile(user.id);
}
}
+54
View File
@@ -0,0 +1,54 @@
import { Module, forwardRef } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { UsersModule } from '../users/users.module';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { PasswordService } from './services/password.service';
import { TokenService } from './services/token.service';
import { JwtStrategy } from './strategies/jwt.strategy';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { RolesGuard } from './guards/roles.guard';
import { InquiryAccessGuard } from './guards/inquiry-access.guard';
import { ApiKeyGuard } from './guards/api-key.guard';
/**
* Authentication & authorization — JWT, RBAC, inquiry access.
* ApiKeyGuard retained for future M2M auth alongside JWT.
*/
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt-access' }),
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.get<string>('auth.jwtSecret'),
}),
}),
forwardRef(() => UsersModule),
],
controllers: [AuthController],
providers: [
AuthService,
PasswordService,
TokenService,
JwtStrategy,
JwtAuthGuard,
RolesGuard,
InquiryAccessGuard,
ApiKeyGuard,
],
exports: [
AuthService,
PasswordService,
TokenService,
JwtAuthGuard,
RolesGuard,
InquiryAccessGuard,
ApiKeyGuard,
PassportModule,
JwtModule,
],
})
export class AuthModule {}
+158
View File
@@ -0,0 +1,158 @@
import {
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { AuditEvent } from '../common/enums/audit-event.enum';
import { AuditService } from '../audit/audit.service';
import { UsersService, RequestContext } from '../users/users.service';
import { PasswordService } from './services/password.service';
import { TokenService } from './services/token.service';
import { LoginDto } from './dto/login.dto';
import { AuthTokensDto } from './dto/auth-tokens.dto';
import { ProfileDto } from './dto/profile.dto';
import { UserMapper } from '../users/mappers/user.mapper';
import { JwtPayload } from './interfaces/jwt-payload.interface';
import { AuthenticatedUser } from './interfaces/authenticated-user.interface';
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
private readonly passwordService: PasswordService,
private readonly tokenService: TokenService,
private readonly auditService: AuditService,
) {}
async login(dto: LoginDto, context: RequestContext = {}): Promise<AuthTokensDto> {
const user = await this.usersService.findByUsername(dto.username, true);
if (!user) {
await this.auditService.log(AuditEvent.LOGIN_FAILED, {
username: dto.username,
ip: context.ip,
userAgent: context.userAgent,
metadata: { reason: 'invalid_credentials' },
});
throw new UnauthorizedException('Invalid credentials');
}
if (!user.isActive) {
await this.auditFailedLogin(user._id.toString(), user.username, 'inactive', context);
throw new ForbiddenException('Account is inactive');
}
if (user.isBlocked) {
await this.auditFailedLogin(user._id.toString(), user.username, 'blocked', context);
throw new ForbiddenException('Account is blocked');
}
const valid = await this.passwordService.compare(dto.password, user.password);
if (!valid) {
await this.auditFailedLogin(user._id.toString(), user.username, 'invalid_credentials', context);
throw new UnauthorizedException('Invalid credentials');
}
const tokens = await this.issueTokens(user);
await this.usersService.saveRefreshToken(user._id.toString(), tokens.refreshToken);
await this.usersService.recordLogin(user._id.toString());
await this.auditService.log(AuditEvent.LOGIN, {
userId: user._id.toString(),
username: user.username,
ip: context.ip,
userAgent: context.userAgent,
});
return tokens;
}
async refresh(refreshToken: string, context: RequestContext = {}): Promise<AuthTokensDto> {
let payload: { sub: string };
try {
payload = this.tokenService.verifyRefreshToken(refreshToken);
} catch {
throw new UnauthorizedException('Invalid refresh token');
}
const valid = await this.usersService.validateRefreshToken(payload.sub, refreshToken);
if (!valid) {
throw new UnauthorizedException('Invalid refresh token');
}
const user = await this.usersService.findById(payload.sub);
if (!user.isActive) {
throw new ForbiddenException('Account is inactive');
}
if (user.isBlocked) {
throw new ForbiddenException('Account is blocked');
}
const tokens = await this.issueTokens(user);
await this.usersService.saveRefreshToken(user._id.toString(), tokens.refreshToken);
await this.auditService.log(AuditEvent.LOGIN, {
userId: user._id.toString(),
username: user.username,
ip: context.ip,
userAgent: context.userAgent,
metadata: { type: 'refresh' },
});
return tokens;
}
async logout(userId: string, context: RequestContext = {}): Promise<void> {
await this.usersService.clearRefreshToken(userId);
const user = await this.usersService.findById(userId);
await this.auditService.log(AuditEvent.LOGOUT, {
userId,
username: user.username,
ip: context.ip,
userAgent: context.userAgent,
});
}
async getProfile(userId: string): Promise<ProfileDto> {
const user = await this.usersService.findById(userId);
return UserMapper.toProfileDto(user);
}
private async issueTokens(user: {
_id: { toString(): string };
role: JwtPayload['role'];
clientType: JwtPayload['clientType'];
appName: string;
}): Promise<AuthTokensDto> {
const payload: JwtPayload = {
sub: user._id.toString(),
role: user.role,
clientType: user.clientType,
appName: user.appName,
};
const pair = this.tokenService.generateTokenPair(payload);
return {
accessToken: pair.accessToken,
refreshToken: pair.refreshToken,
tokenType: 'Bearer',
expiresIn: 900,
};
}
private async auditFailedLogin(
userId: string,
username: string,
reason: string,
context: RequestContext,
): Promise<void> {
await this.auditService.log(AuditEvent.LOGIN_FAILED, {
userId,
username,
ip: context.ip,
userAgent: context.userAgent,
metadata: { reason },
});
}
}
+4
View File
@@ -0,0 +1,4 @@
export const ROLES_KEY = 'roles';
export const INQUIRY_ACCESS_KEY = 'inquiryAccess';
export const JWT_ACCESS_STRATEGY = 'jwt-access';
export const JWT_REFRESH_STRATEGY = 'jwt-refresh';
@@ -0,0 +1,13 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { Request } from 'express';
import { AuthenticatedUser } from '../interfaces/authenticated-user.interface';
/**
* Injects the authenticated user from the request (set by JwtStrategy).
*/
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): AuthenticatedUser => {
const request = ctx.switchToHttp().getRequest<Request & { user: AuthenticatedUser }>();
return request.user;
},
);
@@ -0,0 +1,10 @@
import { SetMetadata } from '@nestjs/common';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { INQUIRY_ACCESS_KEY } from '../constants/auth.constants';
/**
* Declares which inquiry type an endpoint requires.
* InquiryAccessGuard reads this metadata and checks user.allowedInquiries.
*/
export const InquiryAccess = (inquiryType: InquiryType) =>
SetMetadata(INQUIRY_ACCESS_KEY, inquiryType);
+6
View File
@@ -0,0 +1,6 @@
import { SetMetadata } from '@nestjs/common';
import { Role } from '../../common/enums/role.enum';
import { ROLES_KEY } from '../constants/auth.constants';
/** Restrict route to one or more RBAC roles. Use with RolesGuard. */
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
+15
View File
@@ -0,0 +1,15 @@
import { ApiProperty } from '@nestjs/swagger';
export class AuthTokensDto {
@ApiProperty()
accessToken!: string;
@ApiProperty()
refreshToken!: string;
@ApiProperty({ example: 'Bearer' })
tokenType!: string;
@ApiProperty({ example: 900, description: 'Access token lifetime in seconds' })
expiresIn!: number;
}
+15
View File
@@ -0,0 +1,15 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
export class LoginDto {
@ApiProperty({ example: 'admin' })
@IsString()
@IsNotEmpty()
username!: string;
@ApiProperty({ example: 'SecureP@ssw0rd' })
@IsString()
@IsNotEmpty()
@MinLength(8)
password!: string;
}
+62
View File
@@ -0,0 +1,62 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ClientType } from '../../common/enums/client-type.enum';
import { Role } from '../../common/enums/role.enum';
export class ProfileDto {
@ApiProperty()
id!: string;
@ApiProperty()
fullName!: string;
@ApiProperty()
username!: string;
@ApiProperty()
email!: string;
@ApiPropertyOptional()
mobile?: string;
@ApiProperty({ enum: Role })
role!: Role;
@ApiProperty({ enum: ClientType })
clientType!: ClientType;
@ApiProperty()
appName!: string;
@ApiProperty()
clientName!: string;
@ApiProperty()
isActive!: boolean;
@ApiProperty()
isBlocked!: boolean;
@ApiProperty({ type: [String] })
allowedInquiries!: string[];
@ApiProperty()
requestLimitPerMinute!: number;
@ApiProperty()
requestLimitPerDay!: number;
@ApiProperty()
totalRequests!: number;
@ApiPropertyOptional()
lastLoginAt?: Date;
@ApiPropertyOptional()
passwordChangedAt?: Date;
@ApiProperty()
createdAt!: Date;
@ApiProperty()
updatedAt!: Date;
}
+9
View File
@@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
export class RefreshTokenDto {
@ApiProperty({ description: 'Refresh token from login response' })
@IsString()
@IsNotEmpty()
refreshToken!: string;
}
+34
View File
@@ -0,0 +1,34 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
import { API_KEY_HEADER } from '../../common/constants/app.constants';
/**
* API key authentication for inquiry endpoints.
* Expects x-api-key header matching configured API_KEY.
*/
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private readonly configService: ConfigService) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
const apiKey = request.headers[API_KEY_HEADER] as string | undefined;
const expected = this.configService.get<string>('auth.apiKey');
if (!expected) {
throw new UnauthorizedException('API key authentication is not configured');
}
if (!apiKey || apiKey !== expected) {
throw new UnauthorizedException('Invalid or missing API key');
}
return true;
}
}
+45
View File
@@ -0,0 +1,45 @@
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { ADMIN_ROLES } from '../../common/enums/role.enum';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { INQUIRY_ACCESS_KEY } from '../constants/auth.constants';
import { AuthenticatedUser } from '../interfaces/authenticated-user.interface';
/**
* Validates that the user may call a specific inquiry endpoint.
* ADMIN / SUPER_ADMIN bypass — external USER clients need allowedInquiries.
*/
@Injectable()
export class InquiryAccessGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredInquiry = this.reflector.getAllAndOverride<InquiryType>(INQUIRY_ACCESS_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredInquiry) {
return true;
}
const request = context.switchToHttp().getRequest<Request & { user: AuthenticatedUser }>();
const user = request.user;
if (!user) {
throw new ForbiddenException('Authentication required');
}
if (ADMIN_ROLES.includes(user.role)) {
return true;
}
const inquiryKey = requiredInquiry as string;
if (!user.allowedInquiries.includes(inquiryKey)) {
throw new ForbiddenException(`Access denied for inquiry: ${inquiryKey}`);
}
return true;
}
}
+21
View File
@@ -0,0 +1,21 @@
import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JWT_ACCESS_STRATEGY } from '../constants/auth.constants';
/**
* Protects routes with Passport JWT access strategy.
*/
@Injectable()
export class JwtAuthGuard extends AuthGuard(JWT_ACCESS_STRATEGY) {
override handleRequest<TUser>(
err: Error | null,
user: TUser | false,
_info: unknown,
_context: ExecutionContext,
): TUser {
if (err || !user) {
throw err ?? new UnauthorizedException('Unauthorized');
}
return user;
}
}
+34
View File
@@ -0,0 +1,34 @@
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { ROLES_KEY } from '../constants/auth.constants';
import { AuthenticatedUser } from '../interfaces/authenticated-user.interface';
import { Role } from '../../common/enums/role.enum';
/**
* Enforces @Roles() metadata against the authenticated user's role.
*/
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles?.length) {
return true;
}
const request = context.switchToHttp().getRequest<Request & { user: AuthenticatedUser }>();
const user = request.user;
if (!user || !requiredRoles.includes(user.role)) {
throw new ForbiddenException('Insufficient role permissions');
}
return true;
}
}
@@ -0,0 +1,18 @@
import { ClientType } from '../../common/enums/client-type.enum';
import { Role } from '../../common/enums/role.enum';
/**
* User object attached to the request after JWT validation.
* Subset of the User document — avoids loading sensitive fields on every request.
*/
export interface AuthenticatedUser {
id: string;
username: string;
email: string;
role: Role;
clientType: ClientType;
appName: string;
allowedInquiries: string[];
requestLimitPerMinute: number;
requestLimitPerDay: number;
}
@@ -0,0 +1,13 @@
import { ClientType } from '../../common/enums/client-type.enum';
import { Role } from '../../common/enums/role.enum';
/**
* Claims embedded in access tokens.
* Keep minimal — load full user from DB when needed.
*/
export interface JwtPayload {
sub: string;
role: Role;
clientType: ClientType;
appName: string;
}
+21
View File
@@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as bcrypt from 'bcrypt';
/**
* Password hashing — single responsibility for bcrypt operations.
* Future: argon2, password history, complexity rules.
*/
@Injectable()
export class PasswordService {
constructor(private readonly configService: ConfigService) {}
async hash(plain: string): Promise<string> {
const rounds = this.configService.get<number>('auth.bcryptSaltRounds', 12);
return bcrypt.hash(plain, rounds);
}
async compare(plain: string, hash: string): Promise<boolean> {
return bcrypt.compare(plain, hash);
}
}
+50
View File
@@ -0,0 +1,50 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from '../interfaces/jwt-payload.interface';
export interface TokenPair {
accessToken: string;
refreshToken: string;
}
/**
* JWT issuance — access and refresh tokens with separate secrets.
*/
@Injectable()
export class TokenService {
constructor(
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
) {}
generateAccessToken(payload: JwtPayload): string {
return this.jwtService.sign(payload as object, {
secret: this.configService.getOrThrow<string>('auth.jwtSecret'),
expiresIn: this.configService.get<string>('auth.jwtAccessExpiresIn', '15m') as `${number}m`,
});
}
generateRefreshToken(payload: Pick<JwtPayload, 'sub'>): string {
return this.jwtService.sign(
{ sub: payload.sub },
{
secret: this.configService.getOrThrow<string>('auth.jwtRefreshSecret'),
expiresIn: this.configService.get<string>('auth.jwtRefreshExpiresIn', '7d') as `${number}d`,
},
);
}
generateTokenPair(payload: JwtPayload): TokenPair {
return {
accessToken: this.generateAccessToken(payload),
refreshToken: this.generateRefreshToken({ sub: payload.sub }),
};
}
verifyRefreshToken(token: string): Pick<JwtPayload, 'sub'> {
return this.jwtService.verify(token, {
secret: this.configService.getOrThrow<string>('auth.jwtRefreshSecret'),
});
}
}
+48
View File
@@ -0,0 +1,48 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JWT_ACCESS_STRATEGY } from '../constants/auth.constants';
import { JwtPayload } from '../interfaces/jwt-payload.interface';
import { AuthenticatedUser } from '../interfaces/authenticated-user.interface';
import { UsersService } from '../../users/users.service';
/**
* Validates access JWT and attaches a slim user object to the request.
*/
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, JWT_ACCESS_STRATEGY) {
constructor(
configService: ConfigService,
private readonly usersService: UsersService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.getOrThrow<string>('auth.jwtSecret'),
});
}
async validate(payload: JwtPayload): Promise<AuthenticatedUser> {
const user = await this.usersService.findById(payload.sub);
if (!user.isActive) {
throw new UnauthorizedException('Account is inactive');
}
if (user.isBlocked) {
throw new UnauthorizedException('Account is blocked');
}
return {
id: user._id.toString(),
username: user.username,
email: user.email,
role: user.role,
clientType: user.clientType,
appName: user.appName,
allowedInquiries: user.allowedInquiries,
requestLimitPerMinute: user.requestLimitPerMinute,
requestLimitPerDay: user.requestLimitPerDay,
};
}
}