Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

996
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda