mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-14 18:05:48 +00:00
Add roles to user payload in JWT and refresh token strategies
This commit is contained in:
@ -4,4 +4,5 @@ export class AuthInterface {
|
||||
uuid: string;
|
||||
sessionId: string;
|
||||
id: number;
|
||||
roles: string[];
|
||||
}
|
||||
|
@ -28,9 +28,10 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
if (validateUser) {
|
||||
return {
|
||||
email: payload.email,
|
||||
userId: payload.id,
|
||||
userUuid: payload.uuid,
|
||||
uuid: payload.uuid,
|
||||
sessionId: payload.sessionId,
|
||||
roles: payload.roles,
|
||||
};
|
||||
} else {
|
||||
throw new BadRequestException('Unauthorized');
|
||||
|
@ -31,9 +31,10 @@ export class RefreshTokenStrategy extends PassportStrategy(
|
||||
if (validateUser) {
|
||||
return {
|
||||
email: payload.email,
|
||||
userId: payload.id,
|
||||
userUuid: payload.uuid,
|
||||
uuid: payload.uuid,
|
||||
sessionId: payload.sessionId,
|
||||
roles: payload.roles,
|
||||
};
|
||||
} else {
|
||||
throw new BadRequestException('Unauthorized');
|
||||
|
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