This commit is contained in:
2025-11-19 00:27:20 +03:30
parent d764a67fec
commit ef87a1ae6d
+33 -16
View File
@@ -36,21 +36,21 @@ export class AdminAuthGuard implements CanActivate {
async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest<AdminAuthRequest>();
const token = this.extractTokenFromHeader(request);
if (!token) {
this.logger.warn('No token provided');
throw new UnauthorizedException('No token provided');
}
try {
const secret = this.configService.get<string>('JWT_SECRET');
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
// Verify token - JWT module is global, so it uses the configured secret automatically
const payload = await this.jwtService.verifyAsync<IAdminTokenPayload>(token);
if (!payload.adminId || !payload.restId) {
this.logger.error('Invalid token payload structure', payload);
throw new UnauthorizedException('Invalid token payload');
}
const payload = await this.jwtService
.verifyAsync<IAdminTokenPayload>(token, {
secret,
})
.catch(err => {
this.logger.error('error in AdminAuthGuard', err);
throw new UnauthorizedException('Invalid or expired token');
});
request['adminId'] = payload.adminId;
request['restId'] = payload.restId;
@@ -58,20 +58,37 @@ export class AdminAuthGuard implements CanActivate {
const requiredPermissions =
this.reflector.getAllAndOverride<string[]>(PERMISSIONS_KEY, [context.getHandler(), context.getClass()]) ?? [];
if (!requiredPermissions || requiredPermissions.length === 0) return true;
if (!requiredPermissions || requiredPermissions.length === 0) {
return true;
}
const adminPermission = await this.permissionsService.getAdminPermissions(payload.adminId, payload.restId);
if (!adminPermission || !Array.isArray(adminPermission)) {
this.logger.error('No permissions found');
this.logger.error('No permissions found', { adminId: payload.adminId, restId: payload.restId });
throw new ForbiddenException('No permissions found');
}
const hasPermission = requiredPermissions.every(p => adminPermission.includes(p));
if (!hasPermission) throw new ForbiddenException('You are not authorized to access this resource');
if (!hasPermission) {
this.logger.warn('Insufficient permissions', {
adminId: payload.adminId,
restId: payload.restId,
required: requiredPermissions,
has: adminPermission,
});
throw new ForbiddenException('You are not authorized to access this resource');
}
return true;
} catch (err) {
this.logger.error('error in AdminAuthGuard', err);
if (err instanceof ForbiddenException || err instanceof UnauthorizedException) {
throw err;
}
this.logger.error('Token verification error in AdminAuthGuard', {
error: err.message,
stack: err.stack,
});
throw new UnauthorizedException('Invalid or expired token');
}
}