diff --git a/src/guard/role.guard.ts b/src/guard/role.guard.ts index 29791af..a0db94e 100644 --- a/src/guard/role.guard.ts +++ b/src/guard/role.guard.ts @@ -6,20 +6,25 @@ export class RoleGuard implements CanActivate { constructor( private jwtService: JwtService, ) {} + async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const token = request.headers["authorization"]?.split(" ")[1]; if (!token) throw new UnauthorizedException("Authorization token is missing"); + try { const decoded = this.jwtService.verify(token, { secret: process.env.JWT_SECRET }); const userRole = decoded.role; + if (userRole !== "admin") { - throw new UnauthorizedException("You do not have the required role"); + throw new UnauthorizedException(`You do not have the required role. Current role: ${userRole}`); } + request.user = decoded; return true; } catch (error) { - throw new UnauthorizedException("Invalid or expired token"); + console.log(error); + throw new UnauthorizedException(error.response); } } } diff --git a/src/users/users.controller.ts b/src/users/users.controller.ts index 90ea697..6fe56c7 100644 --- a/src/users/users.controller.ts +++ b/src/users/users.controller.ts @@ -5,6 +5,7 @@ import { CreateUserDto } from "./dto/create-user.dto"; import { LoginUserDto } from "./dto/login-user.dto"; import { JwtAuthGuard } from "src/guard/auth.guard"; import { UpdateUserDto } from "./dto/update-user.dto"; +import { RoleGuard } from "src/guard/role.guard"; @Controller("user") export class UsersController { @@ -35,7 +36,7 @@ export class UsersController { return this.usersService.editProfile(userId, updateUserDto); } //get users list (admin) - @UseGuards(JwtAuthGuard) + @UseGuards(RoleGuard) @Get("users") async findAll(): Promise { return this.usersService.findAll(); diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 9ecded9..3adb4e8 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -50,7 +50,7 @@ export class UsersService { } const token = this.jwtService.sign( - { id: user.id }, + { id: user.id,role:user.role }, { secret: this.configService.get("JWT_SECRET"), expiresIn: this.configService.get("JWT_EXPIRES") || "1h",