feat: protecting endpoint by roles

This commit is contained in:
Abdalhamid Alhamad
2024-12-10 10:11:47 +03:00
parent 577f91b796
commit 66e1bb0f28
7 changed files with 53 additions and 10 deletions

View File

@ -0,0 +1,5 @@
import { SetMetadata } from '@nestjs/common';
import { Roles } from '~/auth/enums';
export const ROLE_METADATA_KEY = 'roles';
export const AllowedRoles = (...roles: Roles[]) => SetMetadata(ROLE_METADATA_KEY, roles);

View File

@ -1,2 +1,3 @@
export * from './allowed-roles.decorator';
export * from './public.decorator'; export * from './public.decorator';
export * from './user.decorator'; export * from './user.decorator';

View File

@ -6,7 +6,7 @@ import { IS_PUBLIC_KEY } from '../decorators';
@Injectable() @Injectable()
export class AccessTokenGuard extends AuthGuard('access-token') { export class AccessTokenGuard extends AuthGuard('access-token') {
constructor(private reflector: Reflector) { constructor(protected reflector: Reflector) {
super(); super();
} }
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> { canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {

View File

@ -1 +1,2 @@
export * from './access-token.guard'; export * from './access-token.guard';
export * from './roles-guard';

View File

@ -0,0 +1,28 @@
import { ExecutionContext, Injectable } from '@nestjs/common';
import { Roles } from '~/auth/enums';
import { ROLE_METADATA_KEY } from '../decorators';
import { AccessTokenGuard } from './access-token.guard';
@Injectable()
export class RolesGuard extends AccessTokenGuard {
async canActivate(context: ExecutionContext): Promise<boolean> {
await super.canActivate(context);
const request = context.switchToHttp().getRequest();
const user = request.user;
if (!user) {
return false;
}
const allowedRoles = this.reflector.getAllAndOverride<Roles[]>(ROLE_METADATA_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!allowedRoles) {
return true;
}
return allowedRoles.some((role) => user.roles.includes(role));
}
}

View File

@ -1,8 +1,9 @@
import { Body, Controller, Patch, UseGuards } from '@nestjs/common'; import { Body, Controller, Patch, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Roles } from '~/auth/enums';
import { IJwtPayload } from '~/auth/interfaces'; import { IJwtPayload } from '~/auth/interfaces';
import { AuthenticatedUser } from '~/common/decorators'; import { AllowedRoles, AuthenticatedUser } from '~/common/decorators';
import { AccessTokenGuard } from '~/common/guards'; import { AccessTokenGuard, RolesGuard } from '~/common/guards';
import { ResponseFactory } from '~/core/utils'; import { ResponseFactory } from '~/core/utils';
import { UpdateCustomerRequestDto, UpdateNotificationsSettingsRequestDto } from '../dtos/request'; import { UpdateCustomerRequestDto, UpdateNotificationsSettingsRequestDto } from '../dtos/request';
import { CustomerResponseDto, NotificationSettingsResponseDto } from '../dtos/response'; import { CustomerResponseDto, NotificationSettingsResponseDto } from '../dtos/response';
@ -11,11 +12,12 @@ import { CustomerService } from '../services';
@Controller('customers') @Controller('customers')
@ApiTags('Customers') @ApiTags('Customers')
@ApiBearerAuth() @ApiBearerAuth()
@UseGuards(AccessTokenGuard)
export class CustomerController { export class CustomerController {
constructor(private readonly customerService: CustomerService) {} constructor(private readonly customerService: CustomerService) {}
@Patch('') @Patch('')
@UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
async updateCustomer(@AuthenticatedUser() { sub }: IJwtPayload, @Body() body: UpdateCustomerRequestDto) { async updateCustomer(@AuthenticatedUser() { sub }: IJwtPayload, @Body() body: UpdateCustomerRequestDto) {
const customer = await this.customerService.updateCustomer(sub, body); const customer = await this.customerService.updateCustomer(sub, body);
@ -23,6 +25,7 @@ export class CustomerController {
} }
@Patch('settings/notifications') @Patch('settings/notifications')
@UseGuards(AccessTokenGuard)
async updateNotificationSettings( async updateNotificationSettings(
@AuthenticatedUser() { sub }: IJwtPayload, @AuthenticatedUser() { sub }: IJwtPayload,
@Body() body: UpdateNotificationsSettingsRequestDto, @Body() body: UpdateNotificationsSettingsRequestDto,

View File

@ -1,8 +1,9 @@
import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common'; import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Roles } from '~/auth/enums';
import { IJwtPayload } from '~/auth/interfaces'; import { IJwtPayload } from '~/auth/interfaces';
import { AuthenticatedUser } from '~/common/decorators'; import { AllowedRoles, AuthenticatedUser } from '~/common/decorators';
import { AccessTokenGuard } from '~/common/guards'; import { RolesGuard } from '~/common/guards';
import { ApiDataPageResponse, ApiDataResponse } from '~/core/decorators'; import { ApiDataPageResponse, ApiDataResponse } from '~/core/decorators';
import { PageOptionsRequestDto } from '~/core/dtos'; import { PageOptionsRequestDto } from '~/core/dtos';
import { CustomParseUUIDPipe } from '~/core/pipes'; import { CustomParseUUIDPipe } from '~/core/pipes';
@ -18,7 +19,8 @@ export class JuniorController {
constructor(private readonly juniorService: JuniorService) {} constructor(private readonly juniorService: JuniorService) {}
@Post() @Post()
@UseGuards(AccessTokenGuard) @UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(JuniorResponseDto) @ApiDataResponse(JuniorResponseDto)
async createJunior(@Body() body: CreateJuniorRequestDto, @AuthenticatedUser() user: IJwtPayload) { async createJunior(@Body() body: CreateJuniorRequestDto, @AuthenticatedUser() user: IJwtPayload) {
const junior = await this.juniorService.createJuniors(body, user.sub); const junior = await this.juniorService.createJuniors(body, user.sub);
@ -27,7 +29,8 @@ export class JuniorController {
} }
@Get() @Get()
@UseGuards(AccessTokenGuard) @UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@ApiDataPageResponse(JuniorResponseDto) @ApiDataPageResponse(JuniorResponseDto)
async findJuniors(@AuthenticatedUser() user: IJwtPayload, @Query() pageOptions: PageOptionsRequestDto) { async findJuniors(@AuthenticatedUser() user: IJwtPayload, @Query() pageOptions: PageOptionsRequestDto) {
const [juniors, count] = await this.juniorService.findJuniorsByGuardianId(user.sub, pageOptions); const [juniors, count] = await this.juniorService.findJuniorsByGuardianId(user.sub, pageOptions);
@ -43,7 +46,8 @@ export class JuniorController {
} }
@Get(':juniorId') @Get(':juniorId')
@UseGuards(AccessTokenGuard) @UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(JuniorResponseDto) @ApiDataResponse(JuniorResponseDto)
async findJuniorById( async findJuniorById(
@AuthenticatedUser() user: IJwtPayload, @AuthenticatedUser() user: IJwtPayload,
@ -55,7 +59,8 @@ export class JuniorController {
} }
@Post('set-theme') @Post('set-theme')
@UseGuards(AccessTokenGuard) @UseGuards(RolesGuard)
@AllowedRoles(Roles.JUNIOR)
@ApiDataResponse(JuniorResponseDto) @ApiDataResponse(JuniorResponseDto)
async setTheme(@Body() body: SetThemeRequestDto, @AuthenticatedUser() user: IJwtPayload) { async setTheme(@Body() body: SetThemeRequestDto, @AuthenticatedUser() user: IJwtPayload) {
const theme = await this.juniorService.setTheme(body, user.sub); const theme = await this.juniorService.setTheme(body, user.sub);