diff --git a/src/app.module.ts b/src/app.module.ts index f4fef17..504673d 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -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) { diff --git a/src/auth/decorator/roles.decorator.ts b/src/auth/decorator/roles.decorator.ts new file mode 100644 index 0000000..e038e16 --- /dev/null +++ b/src/auth/decorator/roles.decorator.ts @@ -0,0 +1,4 @@ +import { SetMetadata } from '@nestjs/common'; + +export const ROLES_KEY = 'roles'; +export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles); diff --git a/src/auth/keycloak-auth.guard.ts b/src/auth/keycloak-auth.guard.ts index 4820ac9..5aba027 100644 --- a/src/auth/keycloak-auth.guard.ts +++ b/src/auth/keycloak-auth.guard.ts @@ -1,5 +1,6 @@ import { Injectable, UnauthorizedException } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; + import type { JwtPayload } from './keycloak.strategy'; @Injectable() diff --git a/src/auth/keycloak.strategy.ts b/src/auth/keycloak.strategy.ts index b5edbe1..bdaad1d 100644 --- a/src/auth/keycloak.strategy.ts +++ b/src/auth/keycloak.strategy.ts @@ -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, diff --git a/src/auth/roles.guard.ts b/src/auth/roles.guard.ts new file mode 100644 index 0000000..6962e3a --- /dev/null +++ b/src/auth/roles.guard.ts @@ -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( + 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; + } +} diff --git a/src/middleware/logger.middleware.ts b/src/middleware/logger.middleware.ts index daa82b5..63b6072 100644 --- a/src/middleware/logger.middleware.ts +++ b/src/middleware/logger.middleware.ts @@ -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(); } } diff --git a/src/videos/videos.controller.ts b/src/videos/videos.controller.ts index 6ae92b9..8ca7a93 100644 --- a/src/videos/videos.controller.ts +++ b/src/videos/videos.controller.ts @@ -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 { - return this.videosService.delete(Number(id)); - } + // @Delete(':id') + // async delete(@Param('id') id: string): Promise { + // return this.videosService.delete(Number(id)); + // } }