Skip to content

Commit

Permalink
Merge pull request #127 from Trycatch-tv/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
judlup authored Aug 11, 2024
2 parents 8970502 + a11979e commit 3f02ac3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/controllers/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ import {
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ApiBody, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Roles } from 'src/decorators/user/roles.decorator';
import { CreateUserDto } from 'src/dtos/users/createuser.dto';
import { SigninDto } from 'src/dtos/users/signin.dto';
import { SignupDto } from 'src/dtos/users/signup.dto';
import { UpdateUserDto } from 'src/dtos/users/updateuser.dto';
import { Role } from 'src/enum/user/role.enum';
import { RoleGuard } from 'src/guards/user/role.guard';
import { AuthGuard } from 'src/guards/user/user.guard';
import { CreateOneUserResponse } from 'src/responses/users/createOneUser.response';
import { FindOneUserResponse } from 'src/responses/users/findOneUser.response';
Expand Down Expand Up @@ -46,7 +49,8 @@ export class UsersController {
return 'ok';
}

@UseGuards(AuthGuard)
@UseGuards(AuthGuard, RoleGuard)
@Roles(Role.Admin)
@ApiResponse({
status: 200,
description: 'Returns an array of users',
Expand Down
5 changes: 5 additions & 0 deletions src/decorators/user/roles.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { SetMetadata } from '@nestjs/common';
import { Role } from 'src/enum/user/role.enum';

export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
4 changes: 4 additions & 0 deletions src/enum/user/role.enum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export enum Role {
User = 'user',
Admin = 'admin',
}
22 changes: 22 additions & 0 deletions src/guards/user/role.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from 'src/decorators/user/roles.decorator';
import { Role } from 'src/enum/user/role.enum';

@Injectable()
export class RoleGuard implements CanActivate {
constructor(private reflector: Reflector) {}

canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
const isAllowed = requiredRoles.includes(user.role);
return isAllowed;
}
}

0 comments on commit 3f02ac3

Please sign in to comment.