@minimaltech/node-infra
Version:
Minimal Technology NodeJS Infrastructure - Loopback 4 Framework
179 lines • 8.98 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); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var JWTTokenService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.JWTTokenService = void 0;
const services_1 = require("../../../base/services");
const helpers_1 = require("../../../helpers");
const utilities_1 = require("../../../utilities");
const authentication_jwt_1 = require("@loopback/authentication-jwt");
const core_1 = require("@loopback/core");
const rest_1 = require("@loopback/rest");
const security_1 = require("@loopback/security");
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const common_1 = require("../common");
const common_2 = require("../../../common");
let JWTTokenService = JWTTokenService_1 = class JWTTokenService extends services_1.BaseService {
constructor(applicationSecret, jwtSecret, jwtExpiresIn, getTokenExpiresFn) {
super({ scope: JWTTokenService_1.name });
this.applicationSecret = applicationSecret;
this.jwtSecret = jwtSecret;
this.jwtExpiresIn = jwtExpiresIn;
this.getTokenExpiresFn = getTokenExpiresFn;
this.aes = helpers_1.AES.withAlgorithm('aes-256-cbc');
}
// --------------------------------------------------------------------------------------
extractCredentials(request) {
if (!request.headers.authorization) {
throw (0, utilities_1.getError)({
statusCode: 401,
message: 'Unauthorized user! Missing authorization header',
});
}
const authHeaderValue = request.headers.authorization;
if (!authHeaderValue.startsWith(common_1.Authentication.TYPE_BEARER)) {
throw (0, utilities_1.getError)({
statusCode: 401,
message: 'Unauthorized user! Invalid schema of request token!',
});
}
const parts = authHeaderValue.split(' ');
if (parts.length !== 2) {
throw new rest_1.HttpErrors.Unauthorized(`Authorization header value has too many parts. It must follow the pattern: 'Bearer xx.yy.zz' where xx.yy.zz is a valid JWT token.`);
}
return { type: parts[0], token: parts[1] };
}
// --------------------------------------------------------------------------------------
encryptPayload(payload) {
const userKey = this.aes.encrypt('userId', this.applicationSecret);
const rolesKey = this.aes.encrypt('roles', this.applicationSecret);
const clientIdKey = this.aes.encrypt('clientId', this.applicationSecret);
const { userId, roles, clientId = 'NA' } = payload;
return {
[userKey]: this.aes.encrypt(userId.toString(), this.applicationSecret),
[rolesKey]: this.aes.encrypt(JSON.stringify(roles.map(el => `${el.id}|${el.identifier}|${el.priority}`)), this.applicationSecret),
[clientIdKey]: this.aes.encrypt(clientId, this.applicationSecret),
};
}
// --------------------------------------------------------------------------------------
decryptPayload(decodedToken) {
const rs = {};
const jwtFields = new Set(['iat', 'exp']);
for (const encodedAttr in decodedToken) {
if (jwtFields.has(encodedAttr)) {
rs[encodedAttr] = decodedToken[encodedAttr];
continue;
}
const attr = this.aes.decrypt(encodedAttr, this.applicationSecret);
const decryptedValue = this.aes.decrypt(decodedToken[encodedAttr], this.applicationSecret);
switch (attr) {
case 'userId': {
rs.userId = parseInt(decryptedValue);
rs[security_1.securityId] = rs.userId.toString();
break;
}
case 'clientId': {
rs.clientId = decryptedValue;
break;
}
case 'roles': {
rs.roles = JSON.parse(decryptedValue).map(el => {
const [id, identifier, priority] = el.split('|');
return { id, identifier, priority };
});
break;
}
default: {
rs[encodedAttr] = decodedToken[encodedAttr];
break;
}
}
}
return rs;
}
// --------------------------------------------------------------------------------------
verify(opts) {
const { token } = opts;
if (!token) {
this.logger.error('[verify] Missing token for validating request!');
throw new rest_1.HttpErrors.Unauthorized('Invalid request token!');
}
let decodedToken;
try {
decodedToken = jsonwebtoken_1.default.verify(token, this.jwtSecret);
}
catch (error) {
throw new rest_1.HttpErrors.Unauthorized(`Error verifying token : ${error.message}`);
}
try {
return this.decryptPayload(decodedToken);
}
catch (error) {
this.logger.error('[verify] Failed to decode token | Error: %s', error);
throw (0, utilities_1.getError)({
statusCode: 401,
message: 'Invalid token signature | Failed to decode token!',
});
}
}
// --------------------------------------------------------------------------------------
generate(opts) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const { payload, getTokenExpiresFn = () => {
return Number(this.jwtExpiresIn);
}, } = opts;
if (!payload) {
throw (0, utilities_1.getError)({
statusCode: common_2.ResultCodes.RS_4.Unauthorized,
message: 'Error generating token : userProfile is null',
});
}
let token;
const expiresIn = (_b = (yield ((_a = this.getTokenExpiresFn) === null || _a === void 0 ? void 0 : _a.call(this)))) !== null && _b !== void 0 ? _b : getTokenExpiresFn();
try {
token = jsonwebtoken_1.default.sign(this.encryptPayload(payload), this.jwtSecret, { expiresIn });
}
catch (error) {
throw (0, utilities_1.getError)({
statusCode: common_2.ResultCodes.RS_4.Unauthorized,
message: `Error encoding token : ${error}`,
});
}
return token;
});
}
};
exports.JWTTokenService = JWTTokenService;
exports.JWTTokenService = JWTTokenService = JWTTokenService_1 = __decorate([
(0, core_1.injectable)({ scope: core_1.BindingScope.SINGLETON }),
__param(0, (0, core_1.inject)(common_1.AuthenticateKeys.APPLICATION_SECRET)),
__param(1, (0, core_1.inject)(authentication_jwt_1.TokenServiceBindings.TOKEN_SECRET)),
__param(2, (0, core_1.inject)(authentication_jwt_1.TokenServiceBindings.TOKEN_EXPIRES_IN)),
__param(3, (0, core_1.inject)(common_1.AuthenticateKeys.GET_TOKEN_EXPIRES_FN, { optional: true })),
__metadata("design:paramtypes", [String, String, String, Function])
], JWTTokenService);
//# sourceMappingURL=jwt-token.service.js.map