@mridang/nestjs-auth
Version:
A comprehensive Auth.js integration for NestJS applications with TypeScript support, framework-agnostic HTTP adapters, and role-based access control
60 lines • 2.38 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { REQUIRED_ROLES_KEY } from './auth.decorators.js';
/**
* Guard that enforces role-based access control. Works in conjunction
* with the @RequireRoles() decorator to restrict access to routes based on
* user roles stored in the session.
*
* @example
* ```ts
* @Controller('admin')
* @UseGuards(RolesGuard)
* export class AdminController {
* @Get('users')
* @RequireRoles('admin', 'moderator')
* getUsers() {
* // Only users with 'admin' or 'moderator' roles can access
* }
* }
* ```
*/
let RolesGuard = class RolesGuard {
reflector;
constructor(reflector) {
this.reflector = reflector;
//
}
/**
* Determines if the current request should be allowed based on user roles.
*
* @param context - The execution context containing request and handler info
* @returns true if access should be granted, false otherwise
*/
canActivate(context) {
const requiredRoles = this.reflector.getAllAndOverride(REQUIRED_ROLES_KEY, [context.getHandler(), context.getClass()]);
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const request = context
.switchToHttp()
.getRequest();
const userRoles = request.user?.roles ?? [];
return requiredRoles.some((role) => userRoles.includes(role));
}
};
RolesGuard = __decorate([
Injectable(),
__metadata("design:paramtypes", [Reflector])
], RolesGuard);
export { RolesGuard };
//# sourceMappingURL=roles.guard.js.map