Node.js Framework Series — 1.2.8. NestJS — Guards

NestJs Architecture — Guards
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import * as circular from 'circular';
@Injectable()
export class RbacRolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
console.log('RbacRolesGuard controls..');
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
const hasRole = () =>
user.roles.some(role => !!roles.find(item => item === role));
return user && user.roles && hasRole();
}
}
import { SetMetadata } from '@nestjs/common';export const RbacRoles = (...roles: string[]) => SetMetadata('roles', roles);
import { RbacRolesGuard } from './../common/guards/rbac-roles.guard';
import {
Body, Controller, Delete, Get, Param, Post, Put, Query, UseGuards,
} from '@nestjs/common';
import { RbacRoles } from 'src/common/decorators/rbac-roles.decorator';
@UseGuards(RbacRolesGuard)
@Controller('profile')
export class ProfileController {
@Get()
@RbacRoles('admin', 'user', 'seller')
findAll(@Query() query) {
return `This endpoint returns all users (limit: ${query.limit} items)`;
}
@Get(':id')
@RbacRoles('admin', 'user', 'seller')
findOne(@Param('id') id: number) {
return `This endpoint returns a #${id} user`;
}
@Get(':userName')
@RbacRoles('admin', 'user', 'seller')
async getUserDetails(@Param('userName') userName: string) {
return 'returns user details';
}
@Put(':id')
@RbacRoles('admin', 'user')
update(@Param('id') id: string, @Body() updateProfileDto) {
return `This endpoint updates a #${id} user`;
}
@Delete(':id')
@RbacRoles('user')
remove(@Param('id') id: string) {
return `This endpoint removes a #${id} user`;
}
}

Technical Training Coordinator at www.Zero2Hero.Training, Blockchain Developer(Oxford BC Strategy Programme Certified) and an AWS Certified Solution Architect.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store