UNPKG

@adncorp/powerbi-embed-adapter

Version:

A Beasiness Adapter for PowerBi repports

310 lines (275 loc) 9.68 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); /* eslint-disable spellcheck/spell-checker */ var Configs = require('./Configs'); var request = require('request-promise'); var AuthenticationContext = require('adal-node').AuthenticationContext; var PowerBiAdapter = /*#__PURE__*/ function () { /** * @param {*} configs * @param {*} authContext */ function PowerBiAdapter(configs, authContext) { (0, _classCallCheck2["default"])(this, PowerBiAdapter); this.setConfigs(configs || {}); this.setRequestFunction(null); this.authContext = authContext || new AuthenticationContext(this.authorityHostUrl); } /** * @param {Request} requestFunction */ (0, _createClass2["default"])(PowerBiAdapter, [{ key: "setRequestFunction", value: function setRequestFunction(requestFunction) { this.request = requestFunction || request; } }, { key: "setConfigs", value: function setConfigs(configs) { this.pbiUsername = configs.pbiUsername || Configs.GetEnvironmentVariable('PBI_USERNAME'); this.pbiPassword = configs.pbiPassword || Configs.GetEnvironmentVariable('PBI_PASSWORD'); this.pbiRessource = configs.pbiRessource || Configs.GetEnvironmentVariable('PBI_RESSOURCE'); this.pbiClientId = configs.pbiClientId || Configs.GetEnvironmentVariable('PBI_CLIENT_ID'); this.pbiTenant = configs.pbiTenant || Configs.GetEnvironmentVariable('PBI_TENANT'); this.authorityHostUrl = 'https://login.microsoftonline.com/' + this.pbiTenant + '/oauth2/token'; this.authContext = new AuthenticationContext(this.authorityHostUrl); } /** * * @param {Request} body */ }, { key: "getPowerBiEmbedToken", value: function () { var _getPowerBiEmbedToken = (0, _asyncToGenerator2["default"])( /*#__PURE__*/ _regenerator["default"].mark(function _callee(body) { var pbiReqdata, embedTokenResult; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: // validate that all the required config attrbuts are correctly set this.validate(); // check th if (!(body === null || body === undefined)) { _context.next = 3; break; } throw Error({ code: 101, message: 'requette malformée' }); case 3: pbiReqdata = this.setIdentities({ groupId: body.groupId, reportId: body.reportId, embedRequestBody: { accessLevel: 'view' } }, body); _context.next = 6; return this.getAzureAccessToken(); case 6: pbiReqdata.accessToken = _context.sent; _context.next = 9; return this.requestEmbedToken(pbiReqdata); case 9: embedTokenResult = _context.sent; return _context.abrupt("return", { embedUrl: 'https://app.powerbi.com/reportEmbed?reportId=' + pbiReqdata.reportId + '&groupId=' + pbiReqdata.groupId, embedToken: embedTokenResult.token, reportId: pbiReqdata.reportId, tokenType: 'Embed' }); case 11: case "end": return _context.stop(); } } }, _callee, this); })); function getPowerBiEmbedToken(_x) { return _getPowerBiEmbedToken.apply(this, arguments); } return getPowerBiEmbedToken; }() /** * * @param {Object} data */ }, { key: "requestEmbedToken", value: function requestEmbedToken(data) { var options = { method: 'POST', uri: 'https://api.powerbi.com/v1.0/myorg/groups/' + data.groupId + '/reports/' + data.reportId + '/GenerateToken', body: data.embedRequestBody, headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + data.accessToken }, json: true }; var self = this; return new Promise(function (resolve, reject) { self.request(options).then(function (embedTokenResult) { resolve(embedTokenResult); })["catch"](function (err) { reject(new Error(JSON.stringify({ code: 103, error: err }))); }); }); } /** * TODO: describe this function */ }, { key: "getAzureAccessToken", value: function getAzureAccessToken() { var self = this; return new Promise(function (resolve, reject) { self.authContext.acquireTokenWithUsernamePassword(self.pbiRessource, self.pbiUsername, self.pbiPassword, self.pbiClientId, function (err, accessTokenResult) { if (err) { reject(new Error(JSON.stringify({ code: 102, error: err }))); } else { resolve(accessTokenResult.accessToken); } }); }); } /** * this method set the identities to data embededRequestBody key * @param {Object} data : data from PowerBI API * @param {Object} reqBody : body of the Request */ }, { key: "setIdentities", value: function setIdentities(data, reqBody) { var identityKeyMaping = { userId: 'username', roles: 'roles', datasets: 'datasets', customData: 'customData' }; var dataClone = JSON.parse(JSON.stringify(data)); var identity = this.buildIdentityObject(identityKeyMaping, reqBody); if (!this.isEmpty(identity)) { dataClone.embedRequestBody['identities'] = [identity]; } return dataClone; } /** * this method ma the request Body with the identity key and build an identity Object * @param {Object} identityKeyMaping : all key for the identity mapping * @param {Object} requestBody : Body of the request */ }, { key: "buildIdentityObject", value: function buildIdentityObject(identityKeyMaping, requestBody) { if (requestBody !== null && requestBody !== undefined) { return Object.keys(identityKeyMaping).filter(function (x) { return requestBody[x] !== null && requestBody[x] !== undefined; }) // only retrieve the selected identity key found in the request .map(function (x) { var obj = {}; obj[identityKeyMaping[x]] = requestBody[x]; return obj; }) // for each key found get the corresponding sent value .reduce(function (x, y) { return Object.assign(x, y); }, {}); // merge the key/value withing a single dict } else { return {}; } } /** * verify if an object is empty or not * @param {Object} object */ }, { key: "isEmpty", value: function isEmpty(object) { return Object.keys(object).length === 0; } /** * Get all the required attributs */ }, { key: "allRequiredAttributs", value: function allRequiredAttributs() { return this.getAllMatchingRequried(Object.getOwnPropertyNames(this)); } /** * Check if a given attribut matches the required regex expression * @param {string} attribut */ }, { key: "matchRequired", value: function matchRequired(attribut) { return attribut.match(/^pbi.+$/g); } /** * Get all attributs matching the required regex expression * @param {Array} attributs */ }, { key: "getAllMatchingRequried", value: function getAllMatchingRequried(attributs) { return attributs.filter(this.matchRequired); } /** * Check if a given attribut is not set inthe given class instance * @param {string} attribut * @param {Object} object */ }, { key: "attributIsNotSet", value: function attributIsNotSet(attribut, object) { return object[attribut] === null || object[attribut] === undefined; } /** * Get all attributs from the list that are not set in the given Class instance * @param {Array} attributs * @param {Object} object */ }, { key: "getAllNotSetAttributs", value: function getAllNotSetAttributs(attributs, object) { return attributs.filter(function (attribute) { return object.attributIsNotSet(attribute, object); }); } /** * Validate pbi* attributs */ }, { key: "validate", value: function validate() { var requiredAttributs = this.allRequiredAttributs(); var allNotSetAttributs = this.getAllNotSetAttributs(requiredAttributs, this); if (allNotSetAttributs.length > 0) { throw new Error(JSON.stringify({ code: 100, required: allNotSetAttributs, error: allNotSetAttributs.join(',') + ' are required' })); } else { return true; } } }]); return PowerBiAdapter; }(); module.exports = PowerBiAdapter; //# sourceMappingURL=PowerBiAdapter.js.map