nest-phylax
Version:
Security library for NestJS
70 lines • 3.44 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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JwtAuthGuard = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const constants_1 = require("../../common/constants");
const jwt_util_1 = require("../jwt.util");
let JwtAuthGuard = class JwtAuthGuard {
constructor(reflector, options) {
this.reflector = reflector;
this.options = options;
}
async canActivate(context) {
var _a, _b;
const isPublicArgs = this.reflector.getAllAndOverride(constants_1.IS_PUBLIC_KEY, [context.getHandler(), context.getClass()]);
const isPublic = !!isPublicArgs;
const request = context.switchToHttp().getRequest();
if (isPublic) {
return true;
}
let claims;
try {
const jwtUtil = new jwt_util_1.JwtUtil();
const token = request.headers.authorization.split(' ')[1];
const roleRequirement = this.reflector.get('roles', context.getHandler());
if (roleRequirement) {
const role = claims === null || claims === void 0 ? void 0 : claims.role;
if (!role) {
throw new common_1.UnauthorizedException({
message: 'Could not validate token',
});
}
if (!roleRequirement.includes(role)) {
throw new common_1.UnauthorizedException({
message: 'Unauthorized',
description: 'User does not have the required role',
});
}
}
claims = jwtUtil.verifyJwt(token, (_b = (_a = this === null || this === void 0 ? void 0 : this.options) === null || _a === void 0 ? void 0 : _a.accessTokenConfig) === null || _b === void 0 ? void 0 : _b.secretKey);
request.claims = claims;
return true;
}
catch (error) {
throw new common_1.UnauthorizedException({
message: 'Unauthorized',
description: 'Could not validate token',
});
}
}
};
JwtAuthGuard = __decorate([
(0, common_1.Injectable)(),
__param(1, (0, common_1.Inject)(constants_1.JWT_AUTH_MODULE_OPTIONS_TOKEN)),
__metadata("design:paramtypes", [core_1.Reflector, Object])
], JwtAuthGuard);
exports.JwtAuthGuard = JwtAuthGuard;
//# sourceMappingURL=jwt.auth.guard.js.map