Adiciona primeira parte de adicao de roles
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { Module, MiddlewareConsumer } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
@@ -9,6 +9,7 @@ import { AuthModule } from './auth/auth.module';
|
||||
import { VideosController } from './videos/videos.controller';
|
||||
import { UsuariosModule } from './usuarios/usuarios.module';
|
||||
import { LoggerMiddleware } from './middleware/logger.middleware';
|
||||
import { RolesGuard } from './auth/roles.guard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -19,7 +20,7 @@ import { LoggerMiddleware } from './middleware/logger.middleware';
|
||||
UsuariosModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
providers: [AppService, { provide: APP_GUARD, useClass: RolesGuard }],
|
||||
})
|
||||
export class AppModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,7 @@ import { Request, Response, NextFunction } from 'express';
|
||||
@Injectable()
|
||||
export class LoggerMiddleware implements NestMiddleware {
|
||||
use(req: Request, res: Response, next: NextFunction) {
|
||||
console.table({
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
});
|
||||
console.log(`${req.method}: ${req.url}`);
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Delete,
|
||||
Body,
|
||||
Query,
|
||||
UseGuards,
|
||||
@@ -15,13 +14,16 @@ import { VideoResponseDto } from './dto/video-response.dto';
|
||||
import { PaginatedQueryDto, PaginatedResponse } from '../shared/dto/paginated';
|
||||
import { EBooleanPipe } from '../shared/pipe';
|
||||
import { KeycloakAuthGuard } from '../auth/keycloak-auth.guard';
|
||||
import { Roles } from 'src/auth/decorator/roles.decorator';
|
||||
import { RolesGuard } from 'src/auth/roles.guard';
|
||||
|
||||
@Controller('videos')
|
||||
@UseGuards(KeycloakAuthGuard, RolesGuard)
|
||||
export class VideosController {
|
||||
constructor(private readonly videosService: VideosService) {}
|
||||
|
||||
@Get()
|
||||
@UseGuards(KeycloakAuthGuard)
|
||||
@Roles('user', 'admin')
|
||||
async list(
|
||||
@Query() query: PaginatedQueryDto,
|
||||
@Query('situation') situation?: video_situation,
|
||||
@@ -54,8 +56,8 @@ export class VideosController {
|
||||
return this.videosService.update(Number(id), body);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async delete(@Param('id') id: string): Promise<videos> {
|
||||
return this.videosService.delete(Number(id));
|
||||
}
|
||||
// @Delete(':id')
|
||||
// async delete(@Param('id') id: string): Promise<videos> {
|
||||
// return this.videosService.delete(Number(id));
|
||||
// }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user