Files
negareh-api/src/modules/auth/guards/adminAuth.guard.ts
T
morteza b793dad234
deploy to danak / build_and_deploy (push) Has been cancelled
admin perms decorator
2026-07-24 17:16:54 +03:30

114 lines
3.6 KiB
TypeScript

import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
Inject,
Logger,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { IAdminTokenPayload } from '../interfaces/IToken-payload';
import { PERMISSIONS_KEY } from '../../../common/decorators/permissions.decorator';
import { AuthService } from '../services/auth.service';
export interface AdminAuthRequest extends Request {
adminId: string;
permissions: string[];
}
@Injectable()
export class AdminAuthGuard implements CanActivate {
private readonly logger = new Logger(AdminAuthGuard.name);
constructor(
@Inject(JwtService)
private readonly jwtService: JwtService,
@Inject(ConfigService)
private readonly configService: ConfigService,
private readonly authService: AuthService,
private readonly reflector: Reflector,
) { }
async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest<AdminAuthRequest>();
const token = this.extractTokenFromHeader(request);
if (!token) {
this.logger.warn('No token provided', {
hasAuthHeader: !!request.headers.authorization,
authHeader: request.headers.authorization ? 'present' : 'missing',
headers: Object.keys(request.headers),
});
throw new UnauthorizedException('No token provided');
}
try {
// Get the JWT secret from config
const secret = this.configService.getOrThrow<string>('JWT_SECRET');
// Verify token with the secret
const payload = await this.jwtService.verifyAsync<IAdminTokenPayload>(token, {
secret,
});
if (!payload.adminId) {
this.logger.error('Invalid token payload structure', payload);
throw new UnauthorizedException('Invalid token payload');
}
request['adminId'] = payload.adminId;
const adminPermissions = await this.authService.getAdminPermissionsFromCache(payload.adminId);
request['permissions'] = adminPermissions;
// check if the user has the required permissions
const requiredPermissions =
this.reflector.getAllAndOverride<string[]>(PERMISSIONS_KEY, [context.getHandler(), context.getClass()]) ?? [];
if (requiredPermissions.length > 0) {
const hasPermission = requiredPermissions.every(p => adminPermissions.includes(p));
if (!hasPermission) {
this.logger.warn('Insufficient permissions', {
adminId: payload.adminId,
required: requiredPermissions,
has: hasPermission,
});
throw new ForbiddenException('You are not authorized to access this resource');
}
}
return true;
} catch (err) {
if (err instanceof ForbiddenException || err instanceof UnauthorizedException) {
throw err;
}
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
const errorStack = err instanceof Error ? err.stack : undefined;
this.logger.error('Token verification error in AdminAuthGuard', {
error: errorMessage,
stack: errorStack,
});
throw new UnauthorizedException('Invalid or expired token');
}
}
private extractTokenFromHeader(request: Request): string | undefined {
const authHeader = request.headers.authorization || request.headers['authorization'];
if (!authHeader) {
return undefined;
}
const [type, token] = authHeader.split(' ');
if (type?.toLowerCase() !== 'bearer' || !token) {
return undefined;
}
return token;
}
}