super admin

auth guard
This commit is contained in:
2025-12-16 10:11:25 +03:30
parent 83f868ff3d
commit 32ceefb643
@@ -0,0 +1,67 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, Inject, Logger } from '@nestjs/common';
import { Request } from 'express';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class SuperAdminAuthGuard implements CanActivate {
private readonly logger = new Logger(SuperAdminAuthGuard.name);
constructor(
@Inject(ConfigService)
private readonly configService: ConfigService,
) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
try {
const credentials = this.extractBasicAuthCredentials(request);
if (!credentials) {
throw new UnauthorizedException('Basic authentication required');
}
const { username, password } = credentials;
const expectedUsername = this.configService.getOrThrow<string>('SUPER_ADMIN_USERNAME');
const expectedPassword = this.configService.getOrThrow<string>('SUPER_ADMIN_PASSWORD');
if (username !== expectedUsername || password !== expectedPassword) {
this.logger.warn('Invalid super admin credentials attempt', { username });
throw new UnauthorizedException('Invalid credentials');
}
return true;
} catch (err) {
if (err instanceof UnauthorizedException) {
throw err;
}
this.logger.error('error in SuperAdminAuthGuard', err);
throw new UnauthorizedException('Authentication failed');
}
}
private extractBasicAuthCredentials(request: Request): { username: string; password: string } | null {
const authHeader = request.headers.authorization;
if (!authHeader) {
return null;
}
const [type, encoded] = authHeader.split(' ');
if (type?.toLowerCase() !== 'basic' || !encoded) {
return null;
}
try {
const decoded = Buffer.from(encoded, 'base64').toString('utf-8');
const [username, password] = decoded.split(':');
if (!username || !password) {
return null;
}
return { username, password };
} catch (error) {
this.logger.error('Failed to decode Basic Auth credentials', error);
return null;
}
}
}