'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?



Solution 1:[1]

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> {
    // ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zemil