mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-15 18:27:05 +00:00
Add roles to user payload in JWT and refresh token strategies
This commit is contained in:
17
src/guards/admin.role.guard.ts
Normal file
17
src/guards/admin.role.guard.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { BadRequestException, UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
export class AdminRoleGuard extends AuthGuard('jwt') {
|
||||
handleRequest(err, user) {
|
||||
const isAdmin = user.roles.some((role) => role.type === RoleType.ADMIN);
|
||||
if (err || !user) {
|
||||
throw err || new UnauthorizedException();
|
||||
} else {
|
||||
if (!isAdmin) {
|
||||
throw new BadRequestException('Only admin role can access this route');
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
21
src/guards/user.role.guard.ts
Normal file
21
src/guards/user.role.guard.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { BadRequestException, UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
|
||||
export class UserRoleGuard extends AuthGuard('jwt') {
|
||||
handleRequest(err, user) {
|
||||
const isUserOrAdmin = user.roles.some(
|
||||
(role) => role.type === RoleType.ADMIN || role.type === RoleType.USER,
|
||||
);
|
||||
if (err || !user) {
|
||||
throw err || new UnauthorizedException();
|
||||
} else {
|
||||
if (!isUserOrAdmin) {
|
||||
throw new BadRequestException(
|
||||
'Only admin or user role can access this route',
|
||||
);
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user