open-api-aurum-connector2
Version:
Module to connect to the OPEN API Aurum Core
71 lines (57 loc) • 2.69 kB
JavaScript
const { module_name, configurations_key } = require("../utils/Constants.js");
const { logger } = require("../utils/Logger.js");
const CryptoJS = require("crypto-js");
const cryptoAESauth = (form) => {
logger.info(`module-hub-aurum-core-connector :: cryptoAESauth "${module_name}" ...`);
const config = global[configurations_key];
let username = form.username;
let plaintextPassword = form.password;
let tenant_key = config.authentication.tenant_key;
const rawKey = username + ":" + tenant_key;
logger.info(`module-hub-aurum-core-connector :: rawKey: ${rawKey}`);
// Setting key
var pwhash = CryptoJS.SHA1(CryptoJS.enc.Utf8.parse(rawKey));
var key = CryptoJS.enc.Hex.parse(pwhash.toString(CryptoJS.enc.Hex).substr(0, 32));
// Setting AES encryption
var encrypted = CryptoJS.AES.encrypt(plaintextPassword, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
logger.info(`module-hub-aurum-core-connector :: Encrypted: ${encrypted}`);
return encrypted;
};
const login = async (form) => {
try {
//login
logger.info(`module-hub-aurum-core-connector :: login "${module_name}" ...`);
const config = global[configurations_key];
let endpoint = config?.authentication?.endpoint || "";
logger.info(`module-hub-aurum-core-connector :: Logging in to endpoint: ${endpoint}`);
//if form has username and password, encrypt password, and username add loginTenant
if (form.username && form.password) {
form.password = cryptoAESauth(form).toString();
form.username = form.username + config.authentication.loginTenant;
}
logger.info(`module-hub-aurum-core-connector :: Form: ${JSON.stringify(form)}`);
logger.info(`module-hub-aurum-core-connector :: Authorization: Basic ${Buffer.from(config.authentication.client_id + ":" + config.authentication.client_secret).toString("base64")}`);
//INVOKE ENDPOINT, POST, headers: authorization, body: x-www-form-urlencoded (form)
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Basic " + Buffer.from(config.authentication.client_id + ":" + config.authentication.client_secret).toString("base64"),
},
//add body urlencoded
body: new URLSearchParams(form),
});
//PARSE RESPONSE
const responseJson = await response.json();
logger.info(`module-hub-aurum-core-connector :: Response: ${JSON.stringify(responseJson)}`);
//RETURN RESPONSE
return responseJson;
} catch (error) {
logger.error(`Error logging in "${module_name}"`, error);
return null;
}
};
module.exports = login;