|
|
|
@ -6,20 +6,25 @@ export class RoleGuard implements CanActivate { |
|
|
|
|
constructor( |
|
|
|
|
private jwtService: JwtService, |
|
|
|
|
) {} |
|
|
|
|
|
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> { |
|
|
|
|
const request = context.switchToHttp().getRequest(); |
|
|
|
|
const token = request.headers["authorization"]?.split(" ")[1]; |
|
|
|
|
if (!token) throw new UnauthorizedException("Authorization token is missing"); |
|
|
|
|
|
|
|
|
|
try { |
|
|
|
|
const decoded = this.jwtService.verify(token, { secret: process.env.JWT_SECRET }); |
|
|
|
|
const userRole = decoded.role; |
|
|
|
|
|
|
|
|
|
if (userRole !== "admin") { |
|
|
|
|
throw new UnauthorizedException("You do not have the required role"); |
|
|
|
|
throw new UnauthorizedException(`You do not have the required role. Current role: ${userRole}`); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
request.user = decoded; |
|
|
|
|
return true; |
|
|
|
|
} catch (error) { |
|
|
|
|
throw new UnauthorizedException("Invalid or expired token"); |
|
|
|
|
console.log(error); |
|
|
|
|
throw new UnauthorizedException(error.response); |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|