import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { Request } from 'express'; import { AdminUserRecord } from '../interfaces/admin-records.interface'; import { AdminService } from '../admin.service'; @Injectable() export class AdminJwtAuthGuard implements CanActivate { constructor( private readonly jwtService: JwtService, private readonly adminService: AdminService, ) {} async canActivate(context: ExecutionContext): Promise { const request = context .switchToHttp() .getRequest(); const authHeader = request.get('authorization'); const token = authHeader?.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : undefined; if (!token) { throw new UnauthorizedException('Admin not authenticated'); } try { const payload = await this.jwtService.verifyAsync<{ sub: number; type: string; }>(token); if (payload.type !== 'admin') { throw new UnauthorizedException('Admin not authenticated'); } const adminUser = await this.adminService.findAdminById(payload.sub); if (!adminUser || adminUser.status !== 'active') { throw new UnauthorizedException('Admin not authenticated'); } request.adminUser = adminUser; request.adminId = adminUser.id; return true; } catch { throw new UnauthorizedException('Admin not authenticated'); } } }