@3kles/3kles-coreion
Version:
3Kles Generic Ion Service
268 lines (266 loc) • 13.7 kB
JavaScript
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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 __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthService = void 0;
var _3kles_corebe_1 = require("@3kles/3kles-corebe");
var async_mutex_1 = require("async-mutex");
var jwt = __importStar(require("jsonwebtoken"));
var base64 = __importStar(require("base-64"));
var AuthService = /** @class */ (function (_super) {
__extends(AuthService, _super);
function AuthService(params) {
var _this = _super.call(this, params) || this;
_this.deltaTime = +process.env.DELTA_TIME || 1000;
_this.mutex = new async_mutex_1.Mutex();
_this.secretKey = process.env.cs;
_this.httpAPI = new _3kles_corebe_1.HttpApi('https');
_this.httpAPI.setResponseParser(new _3kles_corebe_1.JSONParser());
_this.httpAPI.setErrorParser(new _3kles_corebe_1.JSONParser());
return _this;
}
AuthService.prototype.authenticate = function (req, res, next) {
return __awaiter(this, void 0, void 0, function () {
var response, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.getIONBEServiceToken()];
case 1:
response = _a.sent();
return [2 /*return*/, res.status(200).json(response)];
case 2:
err_1 = _a.sent();
res.status(404).json(err_1);
return [2 /*return*/, next(err_1)];
case 3: return [2 /*return*/];
}
});
});
};
AuthService.prototype.checkAuth = function (req, res, next) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var token, decodedToken, expired, authTokenObj, authToken, authTokenObj, token, err_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 7, , 8]);
if (!req.headers['authorization']) return [3 /*break*/, 4];
token = (req.headers['authorization'].split(' ').length > 1) ? req.headers['authorization'].split(' ')[1] : req.headers['authorization'];
decodedToken = jwt.decode(token, {
complete: true
});
expired = Date.now() >= +((_a = decodedToken === null || decodedToken === void 0 ? void 0 : decodedToken.payload) === null || _a === void 0 ? void 0 : _a.exp) * 1000;
if (!expired) return [3 /*break*/, 2];
return [4 /*yield*/, this.getIONBEServiceToken()];
case 1:
authTokenObj = _b.sent();
authToken = this.formatAuthToken(authTokenObj);
res.set('authorization', authToken);
next();
return [3 /*break*/, 3];
case 2:
next();
_b.label = 3;
case 3: return [3 /*break*/, 6];
case 4: return [4 /*yield*/, this.getIONBEServiceToken()];
case 5:
authTokenObj = _b.sent();
token = this.formatAuthToken(authTokenObj);
res.set('authorization', token);
next();
_b.label = 6;
case 6: return [3 /*break*/, 8];
case 7:
err_2 = _b.sent();
console.error('[Ion Service]: An error occurred while retrieving the token');
console.error(err_2);
res.status(err_2.statusCode || 500).json({ error: 'An error occurred while retrieving the token' });
return [3 /*break*/, 8];
case 8: return [2 /*return*/];
}
});
});
};
AuthService.prototype.getIONBEServiceToken = function () {
return __awaiter(this, void 0, void 0, function () {
var _a, err_3, err_4;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 6, 7, 9]);
return [4 /*yield*/, this.mutex.acquire()];
case 1:
_b.sent();
if (!(!this.token || this.isTokenExpired(this.token))) return [3 /*break*/, 5];
_b.label = 2;
case 2:
_b.trys.push([2, 4, , 5]);
_a = this;
return [4 /*yield*/, this.loadIONBEServiceToken()];
case 3:
_a.token = _b.sent();
return [3 /*break*/, 5];
case 4:
err_3 = _b.sent();
console.error('[Ion Service]: Error authentication=', err_3);
this.token = null;
return [3 /*break*/, 5];
case 5: return [2 /*return*/, this.token];
case 6:
err_4 = _b.sent();
throw err_4;
case 7: return [4 /*yield*/, this.mutex.release()];
case 8:
_b.sent();
return [7 /*endfinally*/];
case 9: return [2 /*return*/];
}
});
});
};
AuthService.prototype.isTokenExpired = function (token) {
var _a;
var decodedToken = jwt.decode(this.formatToken(token), {
complete: true
});
if (!(decodedToken === null || decodedToken === void 0 ? void 0 : decodedToken.payload)) {
if (+(token === null || token === void 0 ? void 0 : token.expireTime) > 0) {
return Date.now() >= +token.expireTime;
}
return true;
}
return Date.now() >= +((_a = decodedToken === null || decodedToken === void 0 ? void 0 : decodedToken.payload) === null || _a === void 0 ? void 0 : _a.exp) * 1000;
};
AuthService.prototype.formatAuthToken = function (tokenObj) {
if (tokenObj.token_type && tokenObj.access_token) {
return tokenObj.token_type + ' ' + tokenObj.access_token;
}
return tokenObj;
};
AuthService.prototype.formatToken = function (tokenObj) {
if (tokenObj.token_type && tokenObj.access_token) {
return tokenObj.access_token;
}
return tokenObj;
};
AuthService.prototype.loadIONBEServiceToken = function () {
var _a;
return __awaiter(this, void 0, void 0, function () {
var ci, cs, combine, cicsbase64, saak, sask, url, hostname, port, path, options1, response, body;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
console.log('[Ion Service]: Loading ION Token');
ci = process.env.ci;
cs = process.env.cs;
combine = ci + ":" + cs;
cicsbase64 = base64.encode("".concat(combine));
saak = encodeURIComponent(process.env.saak);
sask = encodeURIComponent(process.env.sask);
url = new URL(process.env.pu);
hostname = url.hostname;
port = (url.host.split(':').length > 1) ? +url.host.split(':')[1] : 443;
path = url.pathname + process.env.ot;
options1 = {
method: 'POST',
hostname: hostname,
port: port,
path: path,
headers: {
'Cache-Control': 'no-cache',
'Authorization': "Basic ".concat(cicsbase64),
'Content-Type': 'application/x-www-form-urlencoded'
},
form: false,
data: "grant_type=password&username=".concat(saak, "&password=").concat(sask),
rejectUnauthorized: false
};
return [4 /*yield*/, this.httpAPI.executeRequest(options1)];
case 1:
response = _b.sent();
body = (response === null || response === void 0 ? void 0 : response.body) || {};
body.expireTime = Date.now() + ((~~((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.expires_in) - this.deltaTime) * 1000);
return [2 /*return*/, response === null || response === void 0 ? void 0 : response.body];
}
});
});
};
return AuthService;
}(_3kles_corebe_1.AuthToken));
exports.AuthService = AuthService;
//# sourceMappingURL=auth.service.js.map