import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from "@nestjs/common"; import { JwtService } from "@nestjs/jwt"; import { Request } from "express"; import { RoleEnum } from "src/Types&Enums/role.enum"; /** * Verifies a Bearer JWT and restricts access to `super_admin` role only. * Use this guard on all endpoints that should be reachable only by the * super-admin panel. */ @Injectable() export class SuperAdminGuard implements CanActivate { constructor(private readonly jwtService: JwtService) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const token = this.extractTokenFromHeader(request); if (!token) { throw new UnauthorizedException("Token not found"); } let payload: any; try { payload = await this.jwtService.verifyAsync(token, { secret: `${process.env.JWT_SECRET}`, }); } catch { throw new UnauthorizedException("Invalid or expired token"); } if (payload?.role !== RoleEnum.SUPER_ADMIN) { throw new UnauthorizedException("Super-admin access required"); } (request as any).user = payload; (request as any).identity = payload; return true; } private extractTokenFromHeader(request: Request): string | undefined { const [type, token] = request.headers.authorization?.split(" ") ?? []; return type === "Bearer" ? token : undefined; } }