|
| 1 | +import { |
| 2 | + CanActivate, |
| 3 | + ExecutionContext, |
| 4 | + ForbiddenException, |
| 5 | + Injectable, |
| 6 | + UnauthorizedException, |
| 7 | +} from "@nestjs/common"; |
| 8 | + |
| 9 | +import { Scopes, UserRoles } from "../../app-constants"; |
| 10 | + |
| 11 | +@Injectable() |
| 12 | +export class TopcoderReportsGuard implements CanActivate { |
| 13 | + private static readonly adminRoles = new Set( |
| 14 | + Object.values(UserRoles).map((role) => role.toLowerCase()), |
| 15 | + ); |
| 16 | + |
| 17 | + canActivate(context: ExecutionContext): boolean { |
| 18 | + const request = context.switchToHttp().getRequest(); |
| 19 | + const authUser = request.authUser; |
| 20 | + |
| 21 | + if (!authUser) { |
| 22 | + throw new UnauthorizedException("You are not authenticated."); |
| 23 | + } |
| 24 | + |
| 25 | + if (authUser.isMachine) { |
| 26 | + const scopes: string[] = authUser.scopes ?? []; |
| 27 | + if (this.hasRequiredScope(scopes)) { |
| 28 | + return true; |
| 29 | + } |
| 30 | + |
| 31 | + throw new ForbiddenException( |
| 32 | + "You do not have the required permissions to access this resource.", |
| 33 | + ); |
| 34 | + } |
| 35 | + |
| 36 | + const roles: string[] = authUser.roles ?? []; |
| 37 | + if (this.isAdmin(roles)) { |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + throw new ForbiddenException( |
| 42 | + "You do not have the required permissions to access this resource.", |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + private hasRequiredScope(scopes: string[]): boolean { |
| 47 | + const normalizedScopes = scopes.map((scope) => scope?.toLowerCase()); |
| 48 | + return ( |
| 49 | + normalizedScopes.includes(Scopes.TopcoderReports.toLowerCase()) || |
| 50 | + normalizedScopes.includes(Scopes.AllReports.toLowerCase()) |
| 51 | + ); |
| 52 | + } |
| 53 | + |
| 54 | + private isAdmin(roles: string[]): boolean { |
| 55 | + return roles.some((role) => |
| 56 | + TopcoderReportsGuard.adminRoles.has(role?.toLowerCase()), |
| 57 | + ); |
| 58 | + } |
| 59 | +} |
0 commit comments