From 32ceefb6438648fa8d218de9a14b9ec1f822619b Mon Sep 17 00:00:00 2001 From: morteza-mortezai Date: Tue, 16 Dec 2025 10:11:25 +0330 Subject: [PATCH] super admin auth guard --- .../auth/guards/superAdminAuth.guard.ts | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/modules/auth/guards/superAdminAuth.guard.ts diff --git a/src/modules/auth/guards/superAdminAuth.guard.ts b/src/modules/auth/guards/superAdminAuth.guard.ts new file mode 100644 index 0000000..d1692f4 --- /dev/null +++ b/src/modules/auth/guards/superAdminAuth.guard.ts @@ -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(); + + try { + const credentials = this.extractBasicAuthCredentials(request); + if (!credentials) { + throw new UnauthorizedException('Basic authentication required'); + } + + const { username, password } = credentials; + const expectedUsername = this.configService.getOrThrow('SUPER_ADMIN_USERNAME'); + const expectedPassword = this.configService.getOrThrow('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; + } + } +}