@nestdevx/tenant
Version:
Tenant module for multi-tenant NestJS applications.
43 lines • 2.53 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 JwtAuthGuard_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.JwtAuthGuard = void 0;
const common_1 = require("@nestjs/common");
const passport_1 = require("@nestjs/passport");
let JwtAuthGuard = JwtAuthGuard_1 = class JwtAuthGuard extends (0, passport_1.AuthGuard)('jwt') {
canActivate(context) {
const request = context.switchToHttp().getRequest();
const authHeader = request.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Bearer ')) {
throw new common_1.UnauthorizedException('Missing or invalid Authorization header');
}
return super.canActivate(context);
}
handleRequest(err, user, info, context, status) {
common_1.Logger.debug(`JWT Auth Guard: ${JSON.stringify({ err, user, info })}`, JwtAuthGuard_1.name);
const request = context.switchToHttp().getRequest();
if (!user.tenantId && !request.tenant) {
return super.handleRequest(err, user, info, context, status);
}
if (user.tenantId && !request.tenant) {
common_1.Logger.error(`User has tenant id but request is missing tenant information`, JwtAuthGuard_1.name);
throw new common_1.UnauthorizedException('You are not authorized to access this resource for the current tenant');
}
if (user.tenantId !== request.tenant.id) {
common_1.Logger.error(`Unauthorized access attempt by user ${user.email} for tenant ${request.tenant.id}`, JwtAuthGuard_1.name);
throw new common_1.UnauthorizedException('You are not authorized to access this resource for the current tenant');
}
return super.handleRequest(err, user, info, context, status);
}
};
exports.JwtAuthGuard = JwtAuthGuard;
exports.JwtAuthGuard = JwtAuthGuard = JwtAuthGuard_1 = __decorate([
(0, common_1.Injectable)()
], JwtAuthGuard);
//# sourceMappingURL=jwt-auth.guard.js.map