Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

995
Views
NestJS Permissions Guard - the most efficient way

Currently, I'm working on NestJS API. I'd like to prepare Permissions Guard and I have a problem with this. Users can have only one role, one role can have a lot of permissions. Permissions for roles are set on the Admin panel, so role permissions can be often changed. I cannot understand how can I deal with permissions in PermissionGuard. I know that I can check the current state of them in the database, but I think it's not the best way to do that because the database will be queried too often.

What should I do? Any idea?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Works nice. It's a JwtAuthGuard improvement and checking one permission.

import { CanActivate, ExecutionContext, Type, mixin } from '@nestjs/common';

import { EPermission } from '../path-with-your-enum-values';
import { JWTRequestPayload } from '../request-payload-type';
import { JwtAuthGuard } from './jwt-auth.guard';

export const PermissionGuard = (permission: EPermission): Type<CanActivate> => {
    class PermissionGuardMixin extends JwtAuthGuard {
        async canActivate(context: ExecutionContext) {
            await super.canActivate(context);

            const request = context.switchToHttp().getRequest<JWTRequestPayload>();
            const user = request.user;

            if (!user || !user.permissions) {
                return false;
            }

            return user.permissions.includes(permission);
        }
    }

    return mixin(PermissionGuardMixin);
};

And with controller:

@Post(':taskId/moderate')
@UseGuards(PermissionGuard(EPermission.MODERATE))
public async moderate(@Param('taskId') taskId: string): Promise<any> {
    // ...
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!