Adiciona primeira parte de adicao de roles
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
import { Module, MiddlewareConsumer } from '@nestjs/common';
|
import { Module, MiddlewareConsumer } from '@nestjs/common';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { APP_GUARD } from '@nestjs/core';
|
||||||
import { PrismaModule } from './prisma/prisma.module';
|
import { PrismaModule } from './prisma/prisma.module';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
@@ -9,6 +9,7 @@ import { AuthModule } from './auth/auth.module';
|
|||||||
import { VideosController } from './videos/videos.controller';
|
import { VideosController } from './videos/videos.controller';
|
||||||
import { UsuariosModule } from './usuarios/usuarios.module';
|
import { UsuariosModule } from './usuarios/usuarios.module';
|
||||||
import { LoggerMiddleware } from './middleware/logger.middleware';
|
import { LoggerMiddleware } from './middleware/logger.middleware';
|
||||||
|
import { RolesGuard } from './auth/roles.guard';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -19,7 +20,7 @@ import { LoggerMiddleware } from './middleware/logger.middleware';
|
|||||||
UsuariosModule,
|
UsuariosModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [AppService, { provide: APP_GUARD, useClass: RolesGuard }],
|
||||||
})
|
})
|
||||||
export class AppModule {
|
export class AppModule {
|
||||||
configure(consumer: MiddlewareConsumer) {
|
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 { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
import { AuthGuard } from '@nestjs/passport';
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
|
||||||
import type { JwtPayload } from './keycloak.strategy';
|
import type { JwtPayload } from './keycloak.strategy';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
import { PassportStrategy } from '@nestjs/passport';
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||||
|
|
||||||
import * as jwksRsa from 'jwks-rsa';
|
import * as jwksRsa from 'jwks-rsa';
|
||||||
|
|
||||||
export type JwtAudience = string | string[] | undefined;
|
export type JwtAudience = string | string[] | undefined;
|
||||||
@@ -38,7 +39,6 @@ export class KeycloakJwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
|||||||
: 'https://auth.clipperia.com.br';
|
: 'https://auth.clipperia.com.br';
|
||||||
|
|
||||||
super({
|
super({
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
|
|
||||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
secretOrKeyProvider: jwksRsa.passportJwtSecret({
|
secretOrKeyProvider: jwksRsa.passportJwtSecret({
|
||||||
cache: true,
|
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()
|
@Injectable()
|
||||||
export class LoggerMiddleware implements NestMiddleware {
|
export class LoggerMiddleware implements NestMiddleware {
|
||||||
use(req: Request, res: Response, next: NextFunction) {
|
use(req: Request, res: Response, next: NextFunction) {
|
||||||
console.table({
|
console.log(`${req.method}: ${req.url}`);
|
||||||
method: req.method,
|
|
||||||
url: req.url,
|
|
||||||
});
|
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import {
|
|||||||
Get,
|
Get,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Delete,
|
|
||||||
Body,
|
Body,
|
||||||
Query,
|
Query,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
@@ -15,13 +14,16 @@ import { VideoResponseDto } from './dto/video-response.dto';
|
|||||||
import { PaginatedQueryDto, PaginatedResponse } from '../shared/dto/paginated';
|
import { PaginatedQueryDto, PaginatedResponse } from '../shared/dto/paginated';
|
||||||
import { EBooleanPipe } from '../shared/pipe';
|
import { EBooleanPipe } from '../shared/pipe';
|
||||||
import { KeycloakAuthGuard } from '../auth/keycloak-auth.guard';
|
import { KeycloakAuthGuard } from '../auth/keycloak-auth.guard';
|
||||||
|
import { Roles } from 'src/auth/decorator/roles.decorator';
|
||||||
|
import { RolesGuard } from 'src/auth/roles.guard';
|
||||||
|
|
||||||
@Controller('videos')
|
@Controller('videos')
|
||||||
|
@UseGuards(KeycloakAuthGuard, RolesGuard)
|
||||||
export class VideosController {
|
export class VideosController {
|
||||||
constructor(private readonly videosService: VideosService) {}
|
constructor(private readonly videosService: VideosService) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@UseGuards(KeycloakAuthGuard)
|
@Roles('user', 'admin')
|
||||||
async list(
|
async list(
|
||||||
@Query() query: PaginatedQueryDto,
|
@Query() query: PaginatedQueryDto,
|
||||||
@Query('situation') situation?: video_situation,
|
@Query('situation') situation?: video_situation,
|
||||||
@@ -54,8 +56,8 @@ export class VideosController {
|
|||||||
return this.videosService.update(Number(id), body);
|
return this.videosService.update(Number(id), body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Delete(':id')
|
// @Delete(':id')
|
||||||
async delete(@Param('id') id: string): Promise<videos> {
|
// async delete(@Param('id') id: string): Promise<videos> {
|
||||||
return this.videosService.delete(Number(id));
|
// return this.videosService.delete(Number(id));
|
||||||
}
|
// }
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user