UNPKG

@awhere/api

Version:

The awesome aWhere API for JavaScript.

539 lines 24 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; 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 }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchToken = void 0; var axios_1 = __importDefault(require("axios")); var querystring_1 = require("querystring"); var socket_io_client_1 = __importDefault(require("socket.io-client")); var url_1 = require("../../../utils/url"); var utils_1 = require("./utils"); var codeUtil_1 = require("./utils/codeUtil"); var storageUtil_1 = require("./utils/storageUtil"); var interfaces_1 = require("@awhere/interfaces"); var OAuth = /** @class */ (function () { function OAuth(props) { this._signedIn = false; this._remember = true; this._ssoId = props.ssoId || props.appId; this._appId = props.appId; this._aWhereUrl = props.aWhereUrl; this._scope = props.scope || ['*']; this._popup = !!props.popup; this._callbackUrl = props.callbackUrl || undefined; this._popupCallbackUrl = props.popupCallbackUrl || undefined; this._locale = props.locale || undefined; this._codeChallengeMethod = props.codeChallengeMethod || interfaces_1.CodeChallengeMethod.sha256; } Object.defineProperty(OAuth.prototype, "ssoId", { get: function () { return this._ssoId; }, set: function (value) { this._ssoId = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "appId", { get: function () { return this._appId; }, set: function (value) { this._appId = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "aWhereUrl", { get: function () { return this._aWhereUrl; }, set: function (value) { this._aWhereUrl = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "scope", { get: function () { return this._scope; }, set: function (value) { this._scope = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "signedIn", { get: function () { return this._signedIn; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "popup", { get: function () { return this._popup; }, set: function (value) { this._popup = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "callbackUrl", { get: function () { return this._callbackUrl; }, set: function (value) { this._callbackUrl = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "popupCallbackUrl", { get: function () { return this._popupCallbackUrl; }, set: function (value) { this._popupCallbackUrl = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "locale", { get: function () { return this._locale; }, set: function (value) { this._locale = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "codeChallengeMethod", { get: function () { return this._codeChallengeMethod; }, set: function (value) { this._codeChallengeMethod = value; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "codeVerifier", { get: function () { return this._codeVerifier; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "accessToken", { get: function () { return this._accessToken; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "refreshToken", { get: function () { return this._refreshToken; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "expirationDate", { get: function () { return this._expirationDate; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "expired", { get: function () { if (this._signedIn && this._expirationDate) { return this._expirationDate.getTime() > Date.now(); } else { return undefined; } }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "remember", { get: function () { var _a; return (_a = this._remember) !== null && _a !== void 0 ? _a : true; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "request", { get: function () { if (this._signedIn) { if (!this._request) { this._request = axios_1.default.create({ baseURL: "".concat(this._aWhereUrl).concat(utils_1.endpoint.api, "/"), headers: { Authorization: "Bearer ".concat(this._accessToken), }, }); } } else { this._request = undefined; } return this._request; }, enumerable: false, configurable: true }); Object.defineProperty(OAuth.prototype, "socket", { get: function () { if (this._signedIn) { if (!this._socket) { var url = new URL("".concat(this._aWhereUrl).concat(utils_1.endpoint.api, "/realtime")); var path = url.pathname.replace(/(\/\/)/gi, '/').replace(/(\/$)/, ''); this._socket = (0, socket_io_client_1.default)(url.origin, { path: path, query: { token: this._accessToken }, transports: ['websocket'], autoConnect: false, }); } } else { this._socket = undefined; } return this._socket; }, enumerable: false, configurable: true }); OAuth.prototype.toJSON = function () { return { ssoId: this._ssoId, appId: this._appId, aWhereUrl: this._aWhereUrl, scope: this._scope, signedIn: this._signedIn, popup: this._popup, callbackUrl: this._callbackUrl, popupCallbackUrl: this._popupCallbackUrl, locale: this._locale, codeChallengeMethod: this._codeChallengeMethod, codeVerifier: this._codeVerifier, accessToken: this._accessToken, refreshToken: this._refreshToken, expirationDate: this._expirationDate ? this._expirationDate.getTime() : undefined, remember: this._remember, }; }; OAuth.prototype.syncWithStorage = function () { return __awaiter(this, void 0, void 0, function () { var storedOAuth, aWhereUrl, scope, signedIn, codeVerifier, accessToken, refreshToken, expirationDate, remember; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, (0, storageUtil_1.getOAuth)(this._ssoId)]; case 1: storedOAuth = _a.sent(); if (!storedOAuth) return [3 /*break*/, 3]; aWhereUrl = storedOAuth.aWhereUrl, scope = storedOAuth.scope, signedIn = storedOAuth.signedIn, codeVerifier = storedOAuth.codeVerifier, accessToken = storedOAuth.accessToken, refreshToken = storedOAuth.refreshToken, expirationDate = storedOAuth.expirationDate, remember = storedOAuth.remember; if (!(signedIn && this._aWhereUrl === aWhereUrl && this._scope.join(' ') === scope.join(' '))) return [3 /*break*/, 3]; this._signedIn = signedIn; this._codeVerifier = codeVerifier; this._accessToken = accessToken; this._refreshToken = refreshToken; this._remember = remember !== null && remember !== void 0 ? remember : true; if (expirationDate) { this._expirationDate = new Date(expirationDate); } return [4 /*yield*/, (0, storageUtil_1.setOAuth)(this.toJSON())]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; /** * @deprecated use syncWithStorage instead. */ OAuth.prototype.syncWithLocalStorage = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.syncWithStorage()]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; OAuth.prototype.getAuthorizationUrl = function () { return __awaiter(this, arguments, void 0, function (state) { var authorizationUrl, codeChallenge; var _a; if (state === void 0) { state = (0, codeUtil_1.generateState)(); } return __generator(this, function (_b) { switch (_b.label) { case 0: authorizationUrl = ''; if (!(typeof ((_a = crypto === null || crypto === void 0 ? void 0 : crypto.subtle) === null || _a === void 0 ? void 0 : _a.digest) === 'function')) return [3 /*break*/, 2]; this._codeVerifier = (0, codeUtil_1.generateCodeVerifier)(); return [4 /*yield*/, (0, codeUtil_1.generateCodeChallenge)(this._codeVerifier)]; case 1: codeChallenge = _b.sent(); authorizationUrl = "".concat(this._aWhereUrl).concat(utils_1.endpoint.authorization, "?response_type=code&client_id=").concat(this._appId, "&redirect_uri=").concat(this._popup ? this._popupCallbackUrl : this._callbackUrl, "&code_challenge_method=").concat(this._codeChallengeMethod, "&code_challenge=").concat(codeChallenge, "&state=").concat(state, "&locale=").concat(this._locale); return [3 /*break*/, 3]; case 2: authorizationUrl = "".concat(this._aWhereUrl).concat(utils_1.endpoint.authorization, "?response_type=token&client_id=").concat(this._appId, "&redirect_uri=").concat(this._popup ? this._popupCallbackUrl : this._callbackUrl, "&state=").concat(state, "&locale=").concat(this._locale); _b.label = 3; case 3: return [2 /*return*/, authorizationUrl]; } }); }); }; OAuth.prototype.signIn = function () { return __awaiter(this, arguments, void 0, function (forced) { var state, authorizationUrl, error_1; if (forced === void 0) { forced = false; } return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(forced || !this.signedIn)) return [3 /*break*/, 3]; this._signedIn = false; this._accessToken = undefined; this._refreshToken = undefined; this._expirationDate = undefined; state = (0, codeUtil_1.generateState)(); this.getAuthorizationUrl(state); return [4 /*yield*/, this.getAuthorizationUrl(state)]; case 1: authorizationUrl = _a.sent(); return [4 /*yield*/, (0, storageUtil_1.setState)(state, this.toJSON())]; case 2: _a.sent(); if (this._popup) { // to be implemented for Popup flow } else { window.location.replace(authorizationUrl); } return [3 /*break*/, 7]; case 3: if (!this.expired) return [3 /*break*/, 7]; _a.label = 4; case 4: _a.trys.push([4, 6, , 7]); return [4 /*yield*/, this.fetchNewTokens()]; case 5: _a.sent(); return [3 /*break*/, 7]; case 6: error_1 = _a.sent(); this.signIn(true); return [3 /*break*/, 7]; case 7: return [2 /*return*/]; } }); }); }; OAuth.prototype.signOut = function () { var _this = this; return new Promise(function (resolve, reject) { if (_this._accessToken) { axios_1.default .post("".concat(_this._aWhereUrl).concat(utils_1.endpoint.signOut), (0, querystring_1.stringify)({ token: _this._accessToken, }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then(function (response) { var _a; _this._signedIn = false; _this._codeVerifier = undefined; _this._accessToken = undefined; _this._refreshToken = undefined; _this._expirationDate = undefined; (_a = _this._socket) === null || _a === void 0 ? void 0 : _a.close(); _this._socket = undefined; (0, storageUtil_1.removeOAuth)(_this.ssoId).then(function () { resolve(response); }); }) .catch(function (error) { reject(error); }); } else { reject('accessToken not found.'); } }); }; OAuth.prototype.destroy = function () { return this.signOut(); }; OAuth.prototype.fetchNewTokens = function () { var _this = this; return new Promise(function (resolve, reject) { if (_this._refreshToken) { axios_1.default .post("".concat(_this._aWhereUrl).concat(utils_1.endpoint.refreshToken), (0, querystring_1.stringify)({ grant_type: 'refresh_token', client_id: _this._appId, refresh_token: _this._refreshToken, code_verifier: _this._codeVerifier, redirect_uri: _this._popup ? _this._popupCallbackUrl : _this._callbackUrl, }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then(function (response) { var _a = response.data, access_token = _a.access_token, refresh_token = _a.refresh_token, expires_in = _a.expires_in; _this._accessToken = access_token; _this._refreshToken = refresh_token; _this._expirationDate = new Date(Date.now() + expires_in * 1000); (0, storageUtil_1.setOAuth)(_this.toJSON()).then(function () { resolve(response); }); }) .catch(function (error) { reject(error); }); } else { reject('refreshToken not found.'); } }); }; return OAuth; }()); exports.default = OAuth; var fetchToken = function (params) { return new Promise(function (resolve, reject) { return __awaiter(void 0, void 0, void 0, function () { var code, state, remember, ssoId, queryParams, storedOAuth_1, appId_1, aWhereUrl, popup, callbackUrl, popupCallbackUrl, codeVerifier, accessToken, hashParams, storedOAuth; return __generator(this, function (_a) { switch (_a.label) { case 0: remember = true; queryParams = (0, url_1.parseQuery)(params); code = queryParams.code; state = queryParams.state; remember = queryParams.remember === '0' || queryParams.remember === 'false' ? false : true; if (!(!!code && !!state)) return [3 /*break*/, 2]; return [4 /*yield*/, (0, storageUtil_1.getState)(state)]; case 1: storedOAuth_1 = _a.sent(); if (storedOAuth_1) { appId_1 = storedOAuth_1.appId, aWhereUrl = storedOAuth_1.aWhereUrl, popup = storedOAuth_1.popup, callbackUrl = storedOAuth_1.callbackUrl, popupCallbackUrl = storedOAuth_1.popupCallbackUrl, codeVerifier = storedOAuth_1.codeVerifier; axios_1.default .post("".concat(aWhereUrl).concat(utils_1.endpoint.exchangeToken), (0, querystring_1.stringify)({ grant_type: 'authorization_code', client_id: appId_1, code: code, code_verifier: codeVerifier, redirect_uri: popup ? popupCallbackUrl : callbackUrl, }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then(function (response) { var _a = response.data, sso_id = _a.sso_id, access_token = _a.access_token, refresh_token = _a.refresh_token, expires_in = _a.expires_in; (0, storageUtil_1.setOAuth)(__assign(__assign({}, storedOAuth_1), { ssoId: sso_id || appId_1, signedIn: true, accessToken: access_token, refreshToken: refresh_token, expirationDate: Date.now() + expires_in * 1000, remember: remember })).then(function () { resolve(undefined); }); }) .catch(function (error) { reject(error); }); } else { reject('OAuth not found in LocalStorage.'); } return [2 /*return*/]; case 2: hashParams = (0, url_1.parseHash)(params); accessToken = hashParams.access_token; state = hashParams.state; ssoId = hashParams.sso_id; remember = hashParams.remember === '0' || hashParams.remember === 'false' ? false : true; if (!(!!accessToken && !!state)) return [3 /*break*/, 4]; return [4 /*yield*/, (0, storageUtil_1.getState)(state)]; case 3: storedOAuth = _a.sent(); if (storedOAuth) { (0, storageUtil_1.setOAuth)(__assign(__assign({}, storedOAuth), { ssoId: ssoId || storedOAuth.appId, signedIn: true, accessToken: accessToken, remember: remember })).then(function () { resolve(undefined); }); } else { reject('OAuth not found in LocalStorage.'); } return [3 /*break*/, 5]; case 4: reject('location is not valid.'); _a.label = 5; case 5: return [2 /*return*/]; } }); }); }); }; exports.fetchToken = fetchToken; //# sourceMappingURL=OAuth.js.map