Adiciona primeira parte de adicao de roles
This commit is contained in:
4
src/auth/decorator/roles.decorator.ts
Normal file
4
src/auth/decorator/roles.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
import type { JwtPayload } from './keycloak.strategy';
|
||||
|
||||
@Injectable()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
|
||||
import * as jwksRsa from 'jwks-rsa';
|
||||
|
||||
export type JwtAudience = string | string[] | undefined;
|
||||
@@ -38,7 +39,6 @@ export class KeycloakJwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
: 'https://auth.clipperia.com.br';
|
||||
|
||||
super({
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKeyProvider: jwksRsa.passportJwtSecret({
|
||||
cache: true,
|
||||
|
||||
42
src/auth/roles.guard.ts
Normal file
42
src/auth/roles.guard.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from './decorator/roles.decorator';
|
||||
|
||||
import type { JwtPayload } from './keycloak.strategy';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
|
||||
ROLES_KEY,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<{ user: JwtPayload }>();
|
||||
const user = request.user;
|
||||
|
||||
const userRoles: string[] = [
|
||||
...(user?.resource_access?.clipperia?.roles || []),
|
||||
];
|
||||
|
||||
console.log(context);
|
||||
const hasRole = requiredRoles.some((role) => userRoles.includes(role));
|
||||
if (!hasRole) {
|
||||
throw new ForbiddenException(
|
||||
'O usuário não possui permissão para acessar esta rota',
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user