Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1K
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda