UNPKG

fsm-sdk

Version:

Node.JS sdk to interface with SAP Field Service Management APIs.

102 lines 4.91 kB
"use strict"; 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OAuthService = void 0; const polyfills_1 = require("../../polyfills"); const request_options_factory_1 = require("../request-options.factory"); const jwt_decode_1 = require("jwt-decode"); class OAuthService { constructor(_http, _logger = console) { this._http = _http; this._logger = _logger; } _fetchAndSaveToken(config) { return __awaiter(this, void 0, void 0, function* () { const body = new polyfills_1.URLSearchParams(Object.assign({ grant_type: config.authGrantType }, (config.authGrantType === 'password' ? { username: `${config.authAccountName}/${config.authUserName}`, password: config.authPassword } : {}))); const tokenEndpoint = config.oauthEndpoint ? `${config.oauthEndpoint}/token` : `https://${config.baseUrl}/api/oauth2/v2/token`; if (config.debug) { this._logger.error(`DEBUG: fetching token from ${tokenEndpoint}`); } const response = yield this._http.request(tokenEndpoint, { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': `Basic ${polyfills_1.toBase64(`${config.clientIdentifier}:${config.clientSecret}`)}` }, request_options_factory_1.RequestOptionsFactory.getRequestXHeaders(config)), body: body.toString() }); const token = typeof response === 'string' ? JSON.parse(response) : response; const content = jwt_decode_1.jwtDecode(token.access_token); const tokenResponse = Object.assign(Object.assign({}, token), { content, contentType: config.authGrantType === 'password' // what about code? ? 'user' : 'client' }); if (config.debug && config.tokenCacheFilePath) { try { const fs = require('fs'); // inline import for isomorphic fs.writeFileSync(config.tokenCacheFilePath, JSON.stringify(tokenResponse, null, 2)); } catch (error) { this._logger.error(`ERROR: could not create ${config.tokenCacheFilePath}`, error); } } return tokenResponse; }); } _readToken(config) { return __awaiter(this, void 0, void 0, function* () { try { return yield new Promise((resolve, fail) => { if (config.debug && config.tokenCacheFilePath) { const path = require('path'); const token = require(path.resolve(config.tokenCacheFilePath)); return resolve(token); } fail({ code: 'MODULE_NOT_FOUND' }); }); } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { return yield this._fetchAndSaveToken(config); } throw error; } }); } ensureToken(config) { return __awaiter(this, void 0, void 0, function* () { return this._token && this._tokenExpiration && (new Date() < this._tokenExpiration) ? Promise.resolve(this._token) : this._readToken(config) .then(token => this.setToken(token).getToken()); }); } getToken() { return this._token; } setToken(token) { const missing = ['access_token', 'expires_in', 'token_type'] .filter(key => token[key] === undefined || token[key] === null); if (missing.length) { throw new Error(`Invalid token missing required properties [${missing.join(', ')}]`); } this._token = token; this._tokenExpiration = new Date(new Date().getTime() + token.expires_in * 1000); return this; } } exports.OAuthService = OAuthService; //# sourceMappingURL=oauth.service.js.map