first commit
This commit is contained in:
16
myteamwallet_backend/src/roles/entities/role.entity.ts
Normal file
16
myteamwallet_backend/src/roles/entities/role.entity.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Column, Entity, PrimaryColumn } from 'typeorm';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Allow } from 'class-validator';
|
||||
import { EntityHelper } from 'src/utils/entity-helper';
|
||||
|
||||
@Entity()
|
||||
export class Role extends EntityHelper {
|
||||
@ApiProperty({ example: 1 })
|
||||
@PrimaryColumn()
|
||||
id: number;
|
||||
|
||||
@Allow()
|
||||
@ApiProperty({ example: 'Admin' })
|
||||
@Column()
|
||||
name?: string;
|
||||
}
|
||||
3
myteamwallet_backend/src/roles/roles.decorator.ts
Normal file
3
myteamwallet_backend/src/roles/roles.decorator.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const Roles = (roles: number[]) => SetMetadata('roles', roles);
|
||||
4
myteamwallet_backend/src/roles/roles.enum.ts
Normal file
4
myteamwallet_backend/src/roles/roles.enum.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export enum RoleEnum {
|
||||
'admin' = 1,
|
||||
'user' = 2,
|
||||
}
|
||||
20
myteamwallet_backend/src/roles/roles.guard.ts
Normal file
20
myteamwallet_backend/src/roles/roles.guard.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const roles = this.reflector.getAllAndOverride<number[]>('roles', [
|
||||
context.getClass(),
|
||||
context.getHandler(),
|
||||
]);
|
||||
|
||||
if (!roles || !roles.length) {
|
||||
return true;
|
||||
}
|
||||
const request = context.switchToHttp().getRequest();
|
||||
return roles.includes(request.user?.role?.id);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user