@esri/arcgis-rest-auth
Advanced tools
Comparing version 1.13.1 to 1.13.2
/* @preserve | ||
* @esri/arcgis-rest-auth - v1.13.1 - Apache-2.0 | ||
* @esri/arcgis-rest-auth - v1.13.2 - Apache-2.0 | ||
* Copyright (c) 2017-2018 Esri, Inc. | ||
* Mon Oct 15 2018 12:06:22 GMT-0700 (Pacific Daylight Time) | ||
* Fri Nov 02 2018 15:54:15 GMT-0700 (Pacific Daylight Time) | ||
*/ | ||
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@esri/arcgis-rest-request')) : | ||
typeof define === 'function' && define.amd ? define(['exports', '@esri/arcgis-rest-request'], factory) : | ||
(factory((global.arcgisRest = global.arcgisRest || {}),global.arcgisRest)); | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@esri/arcgis-rest-request')) : | ||
typeof define === 'function' && define.amd ? define(['exports', '@esri/arcgis-rest-request'], factory) : | ||
(factory((global.arcgisRest = global.arcgisRest || {}),global.arcgisRest)); | ||
}(this, (function (exports,arcgisRestRequest) { 'use strict'; | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. All rights reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use | ||
this file except in compliance with the License. You may obtain a copy of the | ||
License at http://www.apache.org/licenses/LICENSE-2.0 | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. All rights reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use | ||
this file except in compliance with the License. You may obtain a copy of the | ||
License at http://www.apache.org/licenses/LICENSE-2.0 | ||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED | ||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, | ||
MERCHANTABLITY OR NON-INFRINGEMENT. | ||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED | ||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, | ||
MERCHANTABLITY OR NON-INFRINGEMENT. | ||
See the Apache Version 2.0 License for specific language governing permissions | ||
and limitations under the License. | ||
***************************************************************************** */ | ||
/* global Reflect, Promise */ | ||
See the Apache Version 2.0 License for specific language governing permissions | ||
and limitations under the License. | ||
***************************************************************************** */ | ||
var __assign = Object.assign || function __assign(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; | ||
}; | ||
var __assign = Object.assign || function __assign(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]; | ||
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
function fetchToken(url, requestOptions) { | ||
// TODO: remove union type and type guard next breaking change and just expect IGenerateTokenRequestOptions | ||
var options = requestOptions | ||
.params | ||
? requestOptions | ||
: { params: requestOptions }; | ||
return arcgisRestRequest.request(url, options).then(function (response) { | ||
var r = { | ||
token: response.access_token, | ||
username: response.username, | ||
expires: new Date(Date.now() + (response.expires_in * 60 * 1000 - 60 * 1000)), | ||
ssl: response.ssl === true | ||
}; | ||
if (response.refresh_token) { | ||
r.refreshToken = response.refresh_token; | ||
} | ||
return r; | ||
}); | ||
} | ||
return t; | ||
}; | ||
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
function fetchToken(url, requestOptions) { | ||
// TODO: remove union type and type guard next breaking change and just expect IGenerateTokenRequestOptions | ||
var options = requestOptions | ||
.params | ||
? requestOptions | ||
: { params: requestOptions }; | ||
return arcgisRestRequest.request(url, options).then(function (response) { | ||
var r = { | ||
token: response.access_token, | ||
username: response.username, | ||
expires: new Date(Date.now() + (response.expires_in * 60 * 1000 - 60 * 1000)), | ||
ssl: response.ssl === true | ||
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
/** | ||
* ```js | ||
* // visit https://developers.arcgis.com to generate your own clientid and secret | ||
* const session = new ApplicationSession({ | ||
* clientId: "abc123", | ||
* clientSecret: "sshhhhhh" | ||
* }) | ||
* ``` | ||
* You can use [App Login](/arcgis-rest-/js/guides/node/) to access premium content and services in ArcGIS Online. | ||
* | ||
*/ | ||
var ApplicationSession = /** @class */ (function () { | ||
function ApplicationSession(options) { | ||
this.clientId = options.clientId; | ||
this.clientSecret = options.clientSecret; | ||
this.token = options.token; | ||
this.expires = options.expires; | ||
this.portal = "https://www.arcgis.com/sharing/rest"; | ||
} | ||
// url isnt actually read or passed through. | ||
ApplicationSession.prototype.getToken = function (url, requestOptions) { | ||
if (this.token && this.expires && this.expires.getTime() > Date.now()) { | ||
return Promise.resolve(this.token); | ||
} | ||
if (this._pendingTokenRequest) { | ||
return this._pendingTokenRequest; | ||
} | ||
this._pendingTokenRequest = this.refreshToken(requestOptions); | ||
return this._pendingTokenRequest; | ||
}; | ||
if (response.refresh_token) { | ||
r.refreshToken = response.refresh_token; | ||
} | ||
return r; | ||
}); | ||
} | ||
ApplicationSession.prototype.refreshToken = function (requestOptions) { | ||
var _this = this; | ||
var options = __assign({ params: { | ||
client_id: this.clientId, | ||
client_secret: this.clientSecret, | ||
grant_type: "client_credentials" | ||
} }, requestOptions); | ||
return fetchToken(this.portal + "/oauth2/token/", options).then(function (response) { | ||
_this._pendingTokenRequest = null; | ||
_this.token = response.token; | ||
_this.expires = response.expires; | ||
return response.token; | ||
}); | ||
}; | ||
ApplicationSession.prototype.refreshSession = function () { | ||
var _this = this; | ||
return this.refreshToken().then(function () { return _this; }); | ||
}; | ||
return ApplicationSession; | ||
}()); | ||
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
/** | ||
* ```js | ||
* // visit https://developers.arcgis.com to generate your own clientid and secret | ||
* const session = new ApplicationSession({ | ||
* clientId: "abc123", | ||
* clientSecret: "sshhhhhh" | ||
* }) | ||
* ``` | ||
* You can use [App Login](/arcgis-rest-/js/guides/node/) to access premium content and services in ArcGIS Online. | ||
* | ||
*/ | ||
var ApplicationSession = /** @class */ (function () { | ||
function ApplicationSession(options) { | ||
this.clientId = options.clientId; | ||
this.clientSecret = options.clientSecret; | ||
this.token = options.token; | ||
this.expires = options.expires; | ||
this.portal = "https://www.arcgis.com/sharing/rest"; | ||
} | ||
// url isnt actually read or passed through. | ||
ApplicationSession.prototype.getToken = function (url, requestOptions) { | ||
if (this.token && this.expires && this.expires.getTime() > Date.now()) { | ||
return Promise.resolve(this.token); | ||
/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
function generateToken(url, requestOptions) { | ||
// TODO: remove union type and type guard next breaking change and just expect IGenerateTokenRequestOptions | ||
var options = requestOptions | ||
.params | ||
? requestOptions | ||
: { params: requestOptions }; | ||
/* istanbul ignore else */ | ||
if (typeof window !== "undefined" && | ||
window.location && | ||
window.location.host) { | ||
options.params.referer = window.location.host; | ||
} | ||
if (this._pendingTokenRequest) { | ||
return this._pendingTokenRequest; | ||
else { | ||
options.params.referer = "@esri.arcgis-rest-auth"; | ||
} | ||
this._pendingTokenRequest = this.refreshToken(requestOptions); | ||
return this._pendingTokenRequest; | ||
}; | ||
ApplicationSession.prototype.refreshToken = function (requestOptions) { | ||
var _this = this; | ||
var options = __assign({ params: { | ||
client_id: this.clientId, | ||
client_secret: this.clientSecret, | ||
grant_type: "client_credentials" | ||
} }, requestOptions); | ||
return fetchToken(this.portal + "/oauth2/token/", options).then(function (response) { | ||
_this._pendingTokenRequest = null; | ||
_this.token = response.token; | ||
_this.expires = response.expires; | ||
return response.token; | ||
}); | ||
}; | ||
ApplicationSession.prototype.refreshSession = function () { | ||
var _this = this; | ||
return this.refreshToken().then(function () { return _this; }); | ||
}; | ||
return ApplicationSession; | ||
}()); | ||
/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
function generateToken(url, requestOptions) { | ||
// TODO: remove union type and type guard next breaking change and just expect IGenerateTokenRequestOptions | ||
var options = requestOptions | ||
.params | ||
? requestOptions | ||
: { params: requestOptions }; | ||
/* istanbul ignore else */ | ||
if (typeof window !== "undefined" && | ||
window.location && | ||
window.location.host) { | ||
options.params.referer = window.location.host; | ||
return arcgisRestRequest.request(url, options); | ||
} | ||
else { | ||
options.params.referer = "@esri.arcgis-rest-auth"; | ||
} | ||
return arcgisRestRequest.request(url, options); | ||
} | ||
/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
function defer() { | ||
var deferred = { | ||
promise: null, | ||
resolve: null, | ||
reject: null | ||
}; | ||
deferred.promise = new Promise(function (resolve, reject) { | ||
deferred.resolve = resolve; | ||
deferred.reject = reject; | ||
}); | ||
return deferred; | ||
} | ||
/** | ||
* ```js | ||
* // OAuth 2.0 allows users to sign in directly to arcgis.com or ArcGIS Enterprise | ||
* UserSession.beginOAuth2({ | ||
* // register a new app to create a unique clientId | ||
* clientId: "abc123", | ||
* redirectUri: 'https://yourapp.com/authenticate.html' | ||
* }) | ||
* .then(session) | ||
* // or | ||
* const session = new UserSession({ | ||
* username: "jsmith", | ||
* password: "123456" | ||
* }) | ||
* ``` | ||
* Used to authenticate both ArcGIS Online and ArcGIS Enterprise users. `UserSession` includes helper methods for [OAuth 2.0](/arcgis-rest-js/guides/browser-authentication/) in both browser and server applications. | ||
* | ||
*/ | ||
var UserSession = /** @class */ (function () { | ||
function UserSession(options) { | ||
this.clientId = options.clientId; | ||
this._refreshToken = options.refreshToken; | ||
this._refreshTokenExpires = options.refreshTokenExpires; | ||
this.username = options.username; | ||
this.password = options.password; | ||
this._token = options.token; | ||
this._tokenExpires = options.tokenExpires; | ||
this.portal = options.portal || "https://www.arcgis.com/sharing/rest"; | ||
this.ssl = options.ssl; | ||
this.provider = options.provider || "arcgis"; | ||
this.tokenDuration = options.tokenDuration || 20160; | ||
this.redirectUri = options.redirectUri; | ||
this.refreshTokenTTL = options.refreshTokenTTL || 1440; | ||
this.trustedServers = {}; | ||
this._pendingTokenRequests = {}; | ||
/* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
function defer() { | ||
var deferred = { | ||
promise: null, | ||
resolve: null, | ||
reject: null | ||
}; | ||
deferred.promise = new Promise(function (resolve, reject) { | ||
deferred.resolve = resolve; | ||
deferred.reject = reject; | ||
}); | ||
return deferred; | ||
} | ||
Object.defineProperty(UserSession.prototype, "token", { | ||
/** | ||
* The current ArcGIS Online or ArcGIS Enterprise `token`. | ||
*/ | ||
get: function () { | ||
return this._token; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(UserSession.prototype, "tokenExpires", { | ||
/** | ||
* The expiration time of the current `token`. | ||
*/ | ||
get: function () { | ||
return this._tokenExpires; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(UserSession.prototype, "refreshToken", { | ||
/** | ||
* The current token to ArcGIS Online or ArcGIS Enterprise. | ||
*/ | ||
get: function () { | ||
return this._refreshToken; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(UserSession.prototype, "refreshTokenExpires", { | ||
/** | ||
* The expiration time of the current `refreshToken`. | ||
*/ | ||
get: function () { | ||
return this._refreshTokenExpires; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
/** | ||
* Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is true the | ||
* authentication window will open in a new tab/window otherwise the user will | ||
* be redirected to the authorization page in their current tab. | ||
* ```js | ||
* // OAuth 2.0 allows users to sign in directly to arcgis.com or ArcGIS Enterprise | ||
* UserSession.beginOAuth2({ | ||
* // register a new app to create a unique clientId | ||
* clientId: "abc123", | ||
* redirectUri: 'https://yourapp.com/authenticate.html' | ||
* }) | ||
* .then(session) | ||
* // or | ||
* const session = new UserSession({ | ||
* username: "jsmith", | ||
* password: "123456" | ||
* }) | ||
* ``` | ||
* Used to authenticate both ArcGIS Online and ArcGIS Enterprise users. `UserSession` includes helper methods for [OAuth 2.0](/arcgis-rest-js/guides/browser-authentication/) in both browser and server applications. | ||
* | ||
* @browserOnly | ||
*/ | ||
/* istanbul ignore next */ | ||
UserSession.beginOAuth2 = function (options, win) { | ||
if (win === void 0) { win = window; } | ||
var _a = __assign({ | ||
portal: "https://www.arcgis.com/sharing/rest", | ||
provider: "arcgis", | ||
duration: 20160, | ||
popup: true, | ||
state: options.clientId, | ||
locale: "" | ||
}, options), portal = _a.portal, provider = _a.provider, clientId = _a.clientId, duration = _a.duration, redirectUri = _a.redirectUri, popup = _a.popup, state = _a.state, locale = _a.locale; | ||
var url; | ||
if (provider === "arcgis") { | ||
url = portal + "/oauth2/authorize?client_id=" + clientId + "&response_type=token&expiration=" + duration + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&state=" + state + "&locale=" + locale; | ||
var UserSession = /** @class */ (function () { | ||
function UserSession(options) { | ||
this.clientId = options.clientId; | ||
this._refreshToken = options.refreshToken; | ||
this._refreshTokenExpires = options.refreshTokenExpires; | ||
this.username = options.username; | ||
this.password = options.password; | ||
this._token = options.token; | ||
this._tokenExpires = options.tokenExpires; | ||
this.portal = options.portal || "https://www.arcgis.com/sharing/rest"; | ||
this.ssl = options.ssl; | ||
this.provider = options.provider || "arcgis"; | ||
this.tokenDuration = options.tokenDuration || 20160; | ||
this.redirectUri = options.redirectUri; | ||
this.refreshTokenTTL = options.refreshTokenTTL || 1440; | ||
this.trustedServers = {}; | ||
this._pendingTokenRequests = {}; | ||
} | ||
else { | ||
url = portal + "/oauth2/social/authorize?client_id=" + clientId + "&socialLoginProviderName=" + provider + "&autoAccountCreateForSocial=true&response_type=token&expiration=" + duration + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&state=" + state + "&locale=" + locale; | ||
} | ||
if (!popup) { | ||
win.location.href = url; | ||
return undefined; | ||
} | ||
var session = defer(); | ||
win["__ESRI_REST_AUTH_HANDLER_" + clientId] = function (errorString, oauthInfoString) { | ||
if (errorString) { | ||
var error = JSON.parse(errorString); | ||
session.reject(new arcgisRestRequest.ArcGISAuthError(error.errorMessage, error.error)); | ||
return; | ||
Object.defineProperty(UserSession.prototype, "token", { | ||
/** | ||
* The current ArcGIS Online or ArcGIS Enterprise `token`. | ||
*/ | ||
get: function () { | ||
return this._token; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(UserSession.prototype, "tokenExpires", { | ||
/** | ||
* The expiration time of the current `token`. | ||
*/ | ||
get: function () { | ||
return this._tokenExpires; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(UserSession.prototype, "refreshToken", { | ||
/** | ||
* The current token to ArcGIS Online or ArcGIS Enterprise. | ||
*/ | ||
get: function () { | ||
return this._refreshToken; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(UserSession.prototype, "refreshTokenExpires", { | ||
/** | ||
* The expiration time of the current `refreshToken`. | ||
*/ | ||
get: function () { | ||
return this._refreshTokenExpires; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
/** | ||
* Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is true the | ||
* authentication window will open in a new tab/window otherwise the user will | ||
* be redirected to the authorization page in their current tab. | ||
* | ||
* @browserOnly | ||
*/ | ||
/* istanbul ignore next */ | ||
UserSession.beginOAuth2 = function (options, win) { | ||
if (win === void 0) { win = window; } | ||
var _a = __assign({ | ||
portal: "https://www.arcgis.com/sharing/rest", | ||
provider: "arcgis", | ||
duration: 20160, | ||
popup: true, | ||
state: options.clientId, | ||
locale: "" | ||
}, options), portal = _a.portal, provider = _a.provider, clientId = _a.clientId, duration = _a.duration, redirectUri = _a.redirectUri, popup = _a.popup, state = _a.state, locale = _a.locale; | ||
var url; | ||
if (provider === "arcgis") { | ||
url = portal + "/oauth2/authorize?client_id=" + clientId + "&response_type=token&expiration=" + duration + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&state=" + state + "&locale=" + locale; | ||
} | ||
if (oauthInfoString) { | ||
var oauthInfo = JSON.parse(oauthInfoString); | ||
session.resolve(new UserSession({ | ||
else { | ||
url = portal + "/oauth2/social/authorize?client_id=" + clientId + "&socialLoginProviderName=" + provider + "&autoAccountCreateForSocial=true&response_type=token&expiration=" + duration + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&state=" + state + "&locale=" + locale; | ||
} | ||
if (!popup) { | ||
win.location.href = url; | ||
return undefined; | ||
} | ||
var session = defer(); | ||
win["__ESRI_REST_AUTH_HANDLER_" + clientId] = function (errorString, oauthInfoString) { | ||
if (errorString) { | ||
var error = JSON.parse(errorString); | ||
session.reject(new arcgisRestRequest.ArcGISAuthError(error.errorMessage, error.error)); | ||
return; | ||
} | ||
if (oauthInfoString) { | ||
var oauthInfo = JSON.parse(oauthInfoString); | ||
session.resolve(new UserSession({ | ||
clientId: clientId, | ||
portal: portal, | ||
ssl: oauthInfo.ssl, | ||
token: oauthInfo.token, | ||
tokenExpires: new Date(oauthInfo.expires), | ||
username: oauthInfo.username | ||
})); | ||
} | ||
}; | ||
win.open(url, "oauth-window", "height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes"); | ||
return session.promise; | ||
}; | ||
/** | ||
* Completes a browser-based OAuth 2.0 sign if `options.popup` is true the user | ||
* will be returned to the previous window. Otherwise a new `UserSession` | ||
* will be returned. | ||
* | ||
* @browserOnly | ||
*/ | ||
/* istanbul ignore next */ | ||
UserSession.completeOAuth2 = function (options, win) { | ||
if (win === void 0) { win = window; } | ||
var _a = __assign({ portal: "https://www.arcgis.com/sharing/rest" }, options), portal = _a.portal, clientId = _a.clientId; | ||
function completeSignIn(error, oauthInfo) { | ||
if (win.opener && win.opener.parent) { | ||
win.opener.parent["__ESRI_REST_AUTH_HANDLER_" + clientId](error ? JSON.stringify(error) : undefined, JSON.stringify(oauthInfo)); | ||
win.close(); | ||
return undefined; | ||
} | ||
if (win !== win.parent) { | ||
win.parent["__ESRI_REST_AUTH_HANDLER_" + clientId](error ? JSON.stringify(error) : undefined, JSON.stringify(oauthInfo)); | ||
win.close(); | ||
return undefined; | ||
} | ||
if (error) { | ||
throw new arcgisRestRequest.ArcGISAuthError(error.errorMessage, error.error); | ||
} | ||
return new UserSession({ | ||
clientId: clientId, | ||
@@ -266,398 +301,360 @@ portal: portal, | ||
token: oauthInfo.token, | ||
tokenExpires: new Date(oauthInfo.expires), | ||
tokenExpires: oauthInfo.expires, | ||
username: oauthInfo.username | ||
})); | ||
}); | ||
} | ||
}; | ||
win.open(url, "oauth-window", "height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes"); | ||
return session.promise; | ||
}; | ||
/** | ||
* Completes a browser-based OAuth 2.0 sign if `options.popup` is true the user | ||
* will be returned to the previous window. Otherwise a new `UserSession` | ||
* will be returned. | ||
* | ||
* @browserOnly | ||
*/ | ||
/* istanbul ignore next */ | ||
UserSession.completeOAuth2 = function (options, win) { | ||
if (win === void 0) { win = window; } | ||
var _a = __assign({ portal: "https://www.arcgis.com/sharing/rest" }, options), portal = _a.portal, clientId = _a.clientId; | ||
function completeSignIn(error, oauthInfo) { | ||
if (win.opener && win.opener.parent) { | ||
win.opener.parent["__ESRI_REST_AUTH_HANDLER_" + clientId](error ? JSON.stringify(error) : undefined, JSON.stringify(oauthInfo)); | ||
win.close(); | ||
return undefined; | ||
var match = win.location.href.match(/access_token=(.+)&expires_in=(.+)&username=([^&]+)/); | ||
if (!match) { | ||
var errorMatch = win.location.href.match(/error=(.+)&error_description=(.+)/); | ||
var error = errorMatch[1]; | ||
var errorMessage = decodeURIComponent(errorMatch[2]); | ||
return completeSignIn({ error: error, errorMessage: errorMessage }); | ||
} | ||
if (win !== win.parent) { | ||
win.parent["__ESRI_REST_AUTH_HANDLER_" + clientId](error ? JSON.stringify(error) : undefined, JSON.stringify(oauthInfo)); | ||
win.close(); | ||
return undefined; | ||
} | ||
if (error) { | ||
throw new arcgisRestRequest.ArcGISAuthError(error.errorMessage, error.error); | ||
} | ||
return new UserSession({ | ||
clientId: clientId, | ||
portal: portal, | ||
ssl: oauthInfo.ssl, | ||
token: oauthInfo.token, | ||
tokenExpires: oauthInfo.expires, | ||
username: oauthInfo.username | ||
var token = match[1]; | ||
var expires = new Date(Date.now() + parseInt(match[2], 10) * 1000 - 60 * 1000); | ||
var username = decodeURIComponent(match[3]); | ||
var ssl = win.location.href.indexOf("&ssl=true") > -1 || | ||
win.location.href.indexOf("#ssl=true") > -1; | ||
return completeSignIn(undefined, { | ||
token: token, | ||
expires: expires, | ||
ssl: ssl, | ||
username: username | ||
}); | ||
} | ||
var match = win.location.href.match(/access_token=(.+)&expires_in=(.+)&username=([^&]+)/); | ||
if (!match) { | ||
var errorMatch = win.location.href.match(/error=(.+)&error_description=(.+)/); | ||
var error = errorMatch[1]; | ||
var errorMessage = decodeURIComponent(errorMatch[2]); | ||
return completeSignIn({ error: error, errorMessage: errorMessage }); | ||
} | ||
var token = match[1]; | ||
var expires = new Date(Date.now() + parseInt(match[2], 10) * 1000 - 60 * 1000); | ||
var username = decodeURIComponent(match[3]); | ||
var ssl = win.location.href.indexOf("&ssl=true") > -1 || | ||
win.location.href.indexOf("#ssl=true") > -1; | ||
return completeSignIn(undefined, { | ||
token: token, | ||
expires: expires, | ||
ssl: ssl, | ||
username: username | ||
}); | ||
}; | ||
/** | ||
* Begins a new server-based OAuth 2.0 sign in. This will redirect the user to | ||
* the ArcGIS Online or ArcGIS Enterprise authorization page. | ||
* | ||
* @nodeOnly | ||
*/ | ||
UserSession.authorize = function (options, response) { | ||
var _a = __assign({ portal: "https://arcgis.com/sharing/rest", duration: 20160 }, options), portal = _a.portal, clientId = _a.clientId, duration = _a.duration, redirectUri = _a.redirectUri; | ||
response.writeHead(301, { | ||
Location: portal + "/oauth2/authorize?client_id=" + clientId + "&duration=" + duration + "&response_type=code&redirect_uri=" + encodeURIComponent(redirectUri) | ||
}); | ||
response.end(); | ||
}; | ||
/** | ||
* Completes the server-based OAuth 2.0 sign in process by exchanging the `authorizationCode` | ||
* for a `access_token`. | ||
* | ||
* @nodeOnly | ||
*/ | ||
UserSession.exchangeAuthorizationCode = function (options, authorizationCode) { | ||
var _a = __assign({ | ||
portal: "https://www.arcgis.com/sharing/rest", | ||
refreshTokenTTL: 1440 | ||
}, options), portal = _a.portal, clientId = _a.clientId, redirectUri = _a.redirectUri, refreshTokenTTL = _a.refreshTokenTTL; | ||
return fetchToken(portal + "/oauth2/token", { | ||
grant_type: "authorization_code", | ||
client_id: clientId, | ||
redirect_uri: redirectUri, | ||
code: authorizationCode | ||
}).then(function (response) { | ||
}; | ||
/** | ||
* Begins a new server-based OAuth 2.0 sign in. This will redirect the user to | ||
* the ArcGIS Online or ArcGIS Enterprise authorization page. | ||
* | ||
* @nodeOnly | ||
*/ | ||
UserSession.authorize = function (options, response) { | ||
var _a = __assign({ portal: "https://arcgis.com/sharing/rest", duration: 20160 }, options), portal = _a.portal, clientId = _a.clientId, duration = _a.duration, redirectUri = _a.redirectUri; | ||
response.writeHead(301, { | ||
Location: portal + "/oauth2/authorize?client_id=" + clientId + "&duration=" + duration + "&response_type=code&redirect_uri=" + encodeURIComponent(redirectUri) | ||
}); | ||
response.end(); | ||
}; | ||
/** | ||
* Completes the server-based OAuth 2.0 sign in process by exchanging the `authorizationCode` | ||
* for a `access_token`. | ||
* | ||
* @nodeOnly | ||
*/ | ||
UserSession.exchangeAuthorizationCode = function (options, authorizationCode) { | ||
var _a = __assign({ | ||
portal: "https://www.arcgis.com/sharing/rest", | ||
refreshTokenTTL: 1440 | ||
}, options), portal = _a.portal, clientId = _a.clientId, redirectUri = _a.redirectUri, refreshTokenTTL = _a.refreshTokenTTL; | ||
return fetchToken(portal + "/oauth2/token", { | ||
grant_type: "authorization_code", | ||
client_id: clientId, | ||
redirect_uri: redirectUri, | ||
code: authorizationCode | ||
}).then(function (response) { | ||
return new UserSession({ | ||
clientId: clientId, | ||
portal: portal, | ||
ssl: response.ssl, | ||
redirectUri: redirectUri, | ||
refreshToken: response.refreshToken, | ||
refreshTokenTTL: refreshTokenTTL, | ||
refreshTokenExpires: new Date(Date.now() + (refreshTokenTTL - 1) * 1000), | ||
token: response.token, | ||
tokenExpires: response.expires, | ||
username: response.username | ||
}); | ||
}); | ||
}; | ||
UserSession.deserialize = function (str) { | ||
var options = JSON.parse(str); | ||
return new UserSession({ | ||
clientId: clientId, | ||
portal: portal, | ||
ssl: response.ssl, | ||
redirectUri: redirectUri, | ||
refreshToken: response.refreshToken, | ||
refreshTokenTTL: refreshTokenTTL, | ||
refreshTokenExpires: new Date(Date.now() + (refreshTokenTTL - 1) * 1000), | ||
token: response.token, | ||
tokenExpires: response.expires, | ||
username: response.username | ||
clientId: options.clientId, | ||
refreshToken: options.refreshToken, | ||
refreshTokenExpires: new Date(options.refreshTokenExpires), | ||
username: options.username, | ||
password: options.password, | ||
token: options.token, | ||
tokenExpires: new Date(options.tokenExpires), | ||
portal: options.portal, | ||
ssl: options.ssl, | ||
tokenDuration: options.tokenDuration, | ||
redirectUri: options.redirectUri, | ||
refreshTokenTTL: options.refreshTokenTTL | ||
}); | ||
}); | ||
}; | ||
UserSession.deserialize = function (str) { | ||
var options = JSON.parse(str); | ||
return new UserSession({ | ||
clientId: options.clientId, | ||
refreshToken: options.refreshToken, | ||
refreshTokenExpires: new Date(options.refreshTokenExpires), | ||
username: options.username, | ||
password: options.password, | ||
token: options.token, | ||
tokenExpires: new Date(options.tokenExpires), | ||
portal: options.portal, | ||
ssl: options.ssl, | ||
tokenDuration: options.tokenDuration, | ||
redirectUri: options.redirectUri, | ||
refreshTokenTTL: options.refreshTokenTTL | ||
}); | ||
}; | ||
/** | ||
* Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* | ||
* ```js | ||
* UserSession.fromCredential({ | ||
* userId: "jsmith", | ||
* token: "secret" | ||
* }); | ||
* ``` | ||
* | ||
* @returns UserSession | ||
*/ | ||
UserSession.fromCredential = function (credential) { | ||
return new UserSession({ | ||
portal: credential.server + "/sharing/rest", | ||
ssl: credential.ssl, | ||
token: credential.token, | ||
username: credential.userId, | ||
tokenExpires: new Date(credential.expires) | ||
}); | ||
}; | ||
/** | ||
* Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* | ||
* ```js | ||
* esriId.registerToken(session.toCredential()); | ||
* ``` | ||
* | ||
* @returns ICredential | ||
*/ | ||
UserSession.prototype.toCredential = function () { | ||
return { | ||
expires: this.tokenExpires.getTime(), | ||
server: this.portal, | ||
ssl: this.ssl, | ||
token: this.token, | ||
userId: this.username | ||
}; | ||
}; | ||
/** | ||
* Returns information about the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic. | ||
* | ||
* ```js | ||
* session.getUser() | ||
* .then(response => { | ||
* console.log(response.role); // "org_admin" | ||
* }) | ||
* ``` | ||
* | ||
* @returns A Promise that will resolve with the data from the response. | ||
*/ | ||
UserSession.prototype.getUser = function (requestOptions) { | ||
var _this = this; | ||
if (this._user && this._user.username === this.username) { | ||
return Promise.resolve(this._user); | ||
} | ||
else { | ||
var url = this.portal + "/community/users/" + encodeURIComponent(this.username); | ||
var options = __assign({ httpMethod: "GET", authentication: this }, requestOptions); | ||
return arcgisRestRequest.request(url, options).then(function (response) { | ||
_this._user = response; | ||
return response; | ||
/** | ||
* Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* | ||
* ```js | ||
* UserSession.fromCredential({ | ||
* userId: "jsmith", | ||
* token: "secret" | ||
* }); | ||
* ``` | ||
* | ||
* @returns UserSession | ||
*/ | ||
UserSession.fromCredential = function (credential) { | ||
return new UserSession({ | ||
portal: credential.server + "/sharing/rest", | ||
ssl: credential.ssl, | ||
token: credential.token, | ||
username: credential.userId, | ||
tokenExpires: new Date(credential.expires) | ||
}); | ||
} | ||
}; | ||
/** | ||
* Gets an appropriate token for the given URL. If `portal` is ArcGIS Online and | ||
* the request is to an ArcGIS Online domain `token` will be used. If the request | ||
* is to the current `portal` the current `token` will also be used. However if | ||
* the request is to an unknown server we will validate the server with a request | ||
* to our current `portal`. | ||
*/ | ||
UserSession.prototype.getToken = function (url, requestOptions) { | ||
if (/^https?:\/\/\S+\.arcgis\.com\/sharing\/rest/.test(this.portal) && | ||
/^https?:\/\/\S+\.arcgis\.com.+/.test(url)) { | ||
return this.getFreshToken(requestOptions); | ||
} | ||
else if (new RegExp(this.portal).test(url)) { | ||
return this.getFreshToken(requestOptions); | ||
} | ||
else { | ||
return this.getTokenForServer(url, requestOptions); | ||
} | ||
}; | ||
UserSession.prototype.toJSON = function () { | ||
return { | ||
clientId: this.clientId, | ||
refreshToken: this.refreshToken, | ||
refreshTokenExpires: this.refreshTokenExpires, | ||
username: this.username, | ||
password: this.password, | ||
token: this.token, | ||
tokenExpires: this.tokenExpires, | ||
portal: this.portal, | ||
ssl: this.ssl, | ||
tokenDuration: this.tokenDuration, | ||
redirectUri: this.redirectUri, | ||
refreshTokenTTL: this.refreshTokenTTL | ||
}; | ||
}; | ||
UserSession.prototype.serialize = function () { | ||
return JSON.stringify(this); | ||
}; | ||
/** | ||
* Manually refreshes the current `token` and `tokenExpires`. | ||
*/ | ||
UserSession.prototype.refreshSession = function (requestOptions) { | ||
if (this.username && this.password) { | ||
return this.refreshWithUsernameAndPassword(requestOptions); | ||
} | ||
if (this.clientId && this.refreshToken) { | ||
return this.refreshWithRefreshToken(); | ||
} | ||
return Promise.reject(new arcgisRestRequest.ArcGISAuthError("Unable to refresh token.")); | ||
}; | ||
/** | ||
* Validates that a given URL is properly federated with our current `portal`. | ||
* Attempts to use the internal `trustedServers` cache first. | ||
*/ | ||
UserSession.prototype.getTokenForServer = function (url, requestOptions) { | ||
var _this = this; | ||
// requests to /rest/services/ and /rest/admin/services/ are both valid | ||
var root = url.split(/\/rest(\/admin)?\/services\//)[0]; | ||
var existingToken = this.trustedServers[root]; | ||
if (existingToken && existingToken.expires.getTime() > Date.now()) { | ||
return Promise.resolve(existingToken.token); | ||
} | ||
if (this._pendingTokenRequests[root]) { | ||
return this._pendingTokenRequests[root]; | ||
} | ||
this._pendingTokenRequests[root] = arcgisRestRequest.request(root + "/rest/info") | ||
.then(function (response) { | ||
return response.owningSystemUrl; | ||
}) | ||
.then(function (owningSystemUrl) { | ||
/** | ||
* if this server is not owned by this portal or the stand-alone | ||
* instance of ArcGIS Server doesn't advertise federation, | ||
* bail out with an error since we know we wont | ||
* be able to generate a token | ||
*/ | ||
if (!owningSystemUrl || | ||
!new RegExp(owningSystemUrl).test(_this.portal)) { | ||
throw new arcgisRestRequest.ArcGISAuthError(url + " is not federated with " + _this.portal + ".", "NOT_FEDERATED"); | ||
/** | ||
* Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/). | ||
* | ||
* ```js | ||
* esriId.registerToken(session.toCredential()); | ||
* ``` | ||
* | ||
* @returns ICredential | ||
*/ | ||
UserSession.prototype.toCredential = function () { | ||
return { | ||
expires: this.tokenExpires.getTime(), | ||
server: this.portal, | ||
ssl: this.ssl, | ||
token: this.token, | ||
userId: this.username | ||
}; | ||
}; | ||
/** | ||
* Returns information about the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic. | ||
* | ||
* ```js | ||
* session.getUser() | ||
* .then(response => { | ||
* console.log(response.role); // "org_admin" | ||
* }) | ||
* ``` | ||
* | ||
* @returns A Promise that will resolve with the data from the response. | ||
*/ | ||
UserSession.prototype.getUser = function (requestOptions) { | ||
var _this = this; | ||
if (this._user && this._user.username === this.username) { | ||
return Promise.resolve(this._user); | ||
} | ||
return arcgisRestRequest.request(owningSystemUrl + "/sharing/rest/info", requestOptions); | ||
}) | ||
.then(function (response) { | ||
return response.authInfo.tokenServicesUrl; | ||
}) | ||
.then(function (tokenServicesUrl) { | ||
if (_this.token) { | ||
return generateToken(tokenServicesUrl, { | ||
params: { | ||
token: _this.token, | ||
serverUrl: url, | ||
expiration: _this.tokenDuration | ||
} | ||
}); | ||
// generate an entirely fresh token if necessary | ||
} | ||
else { | ||
return generateToken(tokenServicesUrl, { | ||
params: { | ||
username: _this.username, | ||
password: _this.password, | ||
expiration: _this.tokenDuration | ||
} | ||
}).then(function (response) { | ||
_this._token = response.token; | ||
_this._tokenExpires = new Date(response.expires); | ||
var url = this.portal + "/community/users/" + encodeURIComponent(this.username); | ||
var options = __assign({ httpMethod: "GET", authentication: this }, requestOptions); | ||
return arcgisRestRequest.request(url, options).then(function (response) { | ||
_this._user = response; | ||
return response; | ||
}); | ||
} | ||
}) | ||
.then(function (response) { | ||
_this.trustedServers[root] = { | ||
expires: new Date(response.expires), | ||
token: response.token | ||
}; | ||
/** | ||
* Gets an appropriate token for the given URL. If `portal` is ArcGIS Online and | ||
* the request is to an ArcGIS Online domain `token` will be used. If the request | ||
* is to the current `portal` the current `token` will also be used. However if | ||
* the request is to an unknown server we will validate the server with a request | ||
* to our current `portal`. | ||
*/ | ||
UserSession.prototype.getToken = function (url, requestOptions) { | ||
if (/^https?:\/\/\S+\.arcgis\.com\/sharing\/rest/.test(this.portal) && | ||
/^https?:\/\/\S+\.arcgis\.com.+/.test(url)) { | ||
return this.getFreshToken(requestOptions); | ||
} | ||
else if (new RegExp(this.portal).test(url)) { | ||
return this.getFreshToken(requestOptions); | ||
} | ||
else { | ||
return this.getTokenForServer(url, requestOptions); | ||
} | ||
}; | ||
UserSession.prototype.toJSON = function () { | ||
return { | ||
clientId: this.clientId, | ||
refreshToken: this.refreshToken, | ||
refreshTokenExpires: this.refreshTokenExpires, | ||
username: this.username, | ||
password: this.password, | ||
token: this.token, | ||
tokenExpires: this.tokenExpires, | ||
portal: this.portal, | ||
ssl: this.ssl, | ||
tokenDuration: this.tokenDuration, | ||
redirectUri: this.redirectUri, | ||
refreshTokenTTL: this.refreshTokenTTL | ||
}; | ||
return response.token; | ||
}); | ||
return this._pendingTokenRequests[root]; | ||
}; | ||
/** | ||
* Returns an unexpired token for the current `portal`. | ||
*/ | ||
UserSession.prototype.getFreshToken = function (requestOptions) { | ||
var _this = this; | ||
if (this.token && | ||
this.tokenExpires && | ||
this.tokenExpires.getTime() > Date.now()) { | ||
return Promise.resolve(this.token); | ||
} | ||
if (!this._pendingTokenRequests[this.portal]) { | ||
this._pendingTokenRequests[this.portal] = this.refreshSession(requestOptions).then(function (session) { | ||
_this._pendingTokenRequests[_this.portal] = null; | ||
return session.token; | ||
}; | ||
UserSession.prototype.serialize = function () { | ||
return JSON.stringify(this); | ||
}; | ||
/** | ||
* Manually refreshes the current `token` and `tokenExpires`. | ||
*/ | ||
UserSession.prototype.refreshSession = function (requestOptions) { | ||
if (this.username && this.password) { | ||
return this.refreshWithUsernameAndPassword(requestOptions); | ||
} | ||
if (this.clientId && this.refreshToken) { | ||
return this.refreshWithRefreshToken(); | ||
} | ||
return Promise.reject(new arcgisRestRequest.ArcGISAuthError("Unable to refresh token.")); | ||
}; | ||
/** | ||
* Validates that a given URL is properly federated with our current `portal`. | ||
* Attempts to use the internal `trustedServers` cache first. | ||
*/ | ||
UserSession.prototype.getTokenForServer = function (url, requestOptions) { | ||
var _this = this; | ||
// requests to /rest/services/ and /rest/admin/services/ are both valid | ||
var root = url.split(/\/rest(\/admin)?\/services\//)[0]; | ||
var existingToken = this.trustedServers[root]; | ||
if (existingToken && existingToken.expires.getTime() > Date.now()) { | ||
return Promise.resolve(existingToken.token); | ||
} | ||
if (this._pendingTokenRequests[root]) { | ||
return this._pendingTokenRequests[root]; | ||
} | ||
this._pendingTokenRequests[root] = arcgisRestRequest.request(root + "/rest/info") | ||
.then(function (response) { | ||
return response.owningSystemUrl; | ||
}) | ||
.then(function (owningSystemUrl) { | ||
/** | ||
* if this server is not owned by this portal or the stand-alone | ||
* instance of ArcGIS Server doesn't advertise federation, | ||
* bail out with an error since we know we wont | ||
* be able to generate a token | ||
*/ | ||
if (!owningSystemUrl || | ||
!new RegExp(owningSystemUrl).test(_this.portal)) { | ||
throw new arcgisRestRequest.ArcGISAuthError(url + " is not federated with " + _this.portal + ".", "NOT_FEDERATED"); | ||
} | ||
return arcgisRestRequest.request(owningSystemUrl + "/sharing/rest/info", requestOptions); | ||
}) | ||
.then(function (response) { | ||
return response.authInfo.tokenServicesUrl; | ||
}) | ||
.then(function (tokenServicesUrl) { | ||
if (_this.token) { | ||
return generateToken(tokenServicesUrl, { | ||
params: { | ||
token: _this.token, | ||
serverUrl: url, | ||
expiration: _this.tokenDuration | ||
} | ||
}); | ||
// generate an entirely fresh token if necessary | ||
} | ||
else { | ||
return generateToken(tokenServicesUrl, { | ||
params: { | ||
username: _this.username, | ||
password: _this.password, | ||
expiration: _this.tokenDuration | ||
} | ||
}).then(function (response) { | ||
_this._token = response.token; | ||
_this._tokenExpires = new Date(response.expires); | ||
return response; | ||
}); | ||
} | ||
}) | ||
.then(function (response) { | ||
_this.trustedServers[root] = { | ||
expires: new Date(response.expires), | ||
token: response.token | ||
}; | ||
return response.token; | ||
}); | ||
} | ||
return this._pendingTokenRequests[this.portal]; | ||
}; | ||
/** | ||
* Refreshes the current `token` and `tokenExpires` with `username` and | ||
* `password`. | ||
*/ | ||
UserSession.prototype.refreshWithUsernameAndPassword = function (requestOptions) { | ||
var _this = this; | ||
var options = __assign({ params: { | ||
username: this.username, | ||
password: this.password, | ||
expiration: this.tokenDuration | ||
} }, requestOptions); | ||
return generateToken(this.portal + "/generateToken", options).then(function (response) { | ||
_this._token = response.token; | ||
_this._tokenExpires = new Date(response.expires); | ||
return _this; | ||
}); | ||
}; | ||
/** | ||
* Refreshes the current `token` and `tokenExpires` with `refreshToken`. | ||
*/ | ||
UserSession.prototype.refreshWithRefreshToken = function (requestOptions) { | ||
var _this = this; | ||
if (this.refreshToken && | ||
this.refreshTokenExpires && | ||
this.refreshTokenExpires.getTime() < Date.now()) { | ||
return this.refreshRefreshToken(requestOptions); | ||
} | ||
var options = __assign({ params: { | ||
client_id: this.clientId, | ||
refresh_token: this.refreshToken, | ||
grant_type: "refresh_token" | ||
} }, requestOptions); | ||
return fetchToken(this.portal + "/oauth2/token", options).then(function (response) { | ||
_this._token = response.token; | ||
_this._tokenExpires = response.expires; | ||
return _this; | ||
}); | ||
}; | ||
/** | ||
* Exchanges an expired `refreshToken` for a new one also updates `token` and | ||
* `tokenExpires`. | ||
*/ | ||
UserSession.prototype.refreshRefreshToken = function (requestOptions) { | ||
var _this = this; | ||
var options = __assign({ params: { | ||
client_id: this.clientId, | ||
refresh_token: this.refreshToken, | ||
redirect_uri: this.redirectUri, | ||
grant_type: "exchange_refresh_token" | ||
} }, requestOptions); | ||
return fetchToken(this.portal + "/oauth2/token", options).then(function (response) { | ||
_this._token = response.token; | ||
_this._tokenExpires = response.expires; | ||
_this._refreshToken = response.refreshToken; | ||
_this._refreshTokenExpires = new Date(Date.now() + (_this.refreshTokenTTL - 1) * 60 * 1000); | ||
return _this; | ||
}); | ||
}; | ||
return UserSession; | ||
}()); | ||
return this._pendingTokenRequests[root]; | ||
}; | ||
/** | ||
* Returns an unexpired token for the current `portal`. | ||
*/ | ||
UserSession.prototype.getFreshToken = function (requestOptions) { | ||
var _this = this; | ||
if (this.token && | ||
this.tokenExpires && | ||
this.tokenExpires.getTime() > Date.now()) { | ||
return Promise.resolve(this.token); | ||
} | ||
if (!this._pendingTokenRequests[this.portal]) { | ||
this._pendingTokenRequests[this.portal] = this.refreshSession(requestOptions).then(function (session) { | ||
_this._pendingTokenRequests[_this.portal] = null; | ||
return session.token; | ||
}); | ||
} | ||
return this._pendingTokenRequests[this.portal]; | ||
}; | ||
/** | ||
* Refreshes the current `token` and `tokenExpires` with `username` and | ||
* `password`. | ||
*/ | ||
UserSession.prototype.refreshWithUsernameAndPassword = function (requestOptions) { | ||
var _this = this; | ||
var options = __assign({ params: { | ||
username: this.username, | ||
password: this.password, | ||
expiration: this.tokenDuration | ||
} }, requestOptions); | ||
return generateToken(this.portal + "/generateToken", options).then(function (response) { | ||
_this._token = response.token; | ||
_this._tokenExpires = new Date(response.expires); | ||
return _this; | ||
}); | ||
}; | ||
/** | ||
* Refreshes the current `token` and `tokenExpires` with `refreshToken`. | ||
*/ | ||
UserSession.prototype.refreshWithRefreshToken = function (requestOptions) { | ||
var _this = this; | ||
if (this.refreshToken && | ||
this.refreshTokenExpires && | ||
this.refreshTokenExpires.getTime() < Date.now()) { | ||
return this.refreshRefreshToken(requestOptions); | ||
} | ||
var options = __assign({ params: { | ||
client_id: this.clientId, | ||
refresh_token: this.refreshToken, | ||
grant_type: "refresh_token" | ||
} }, requestOptions); | ||
return fetchToken(this.portal + "/oauth2/token", options).then(function (response) { | ||
_this._token = response.token; | ||
_this._tokenExpires = response.expires; | ||
return _this; | ||
}); | ||
}; | ||
/** | ||
* Exchanges an expired `refreshToken` for a new one also updates `token` and | ||
* `tokenExpires`. | ||
*/ | ||
UserSession.prototype.refreshRefreshToken = function (requestOptions) { | ||
var _this = this; | ||
var options = __assign({ params: { | ||
client_id: this.clientId, | ||
refresh_token: this.refreshToken, | ||
redirect_uri: this.redirectUri, | ||
grant_type: "exchange_refresh_token" | ||
} }, requestOptions); | ||
return fetchToken(this.portal + "/oauth2/token", options).then(function (response) { | ||
_this._token = response.token; | ||
_this._tokenExpires = response.expires; | ||
_this._refreshToken = response.refreshToken; | ||
_this._refreshTokenExpires = new Date(Date.now() + (_this.refreshTokenTTL - 1) * 60 * 1000); | ||
return _this; | ||
}); | ||
}; | ||
return UserSession; | ||
}()); | ||
/* Copyright (c) 2018 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
/* Copyright (c) 2018 Environmental Systems Research Institute, Inc. | ||
* Apache-2.0 */ | ||
exports.ApplicationSession = ApplicationSession; | ||
exports.UserSession = UserSession; | ||
exports.fetchToken = fetchToken; | ||
exports.generateToken = generateToken; | ||
exports.ApplicationSession = ApplicationSession; | ||
exports.UserSession = UserSession; | ||
exports.fetchToken = fetchToken; | ||
exports.generateToken = generateToken; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
}))); | ||
//# sourceMappingURL=auth.umd.js.map |
/* @preserve | ||
* @esri/arcgis-rest-auth - v1.13.1 - Apache-2.0 | ||
* @esri/arcgis-rest-auth - v1.13.2 - Apache-2.0 | ||
* Copyright (c) 2017-2018 Esri, Inc. | ||
* Mon Oct 15 2018 12:06:24 GMT-0700 (Pacific Daylight Time) | ||
* Fri Nov 02 2018 15:54:17 GMT-0700 (Pacific Daylight Time) | ||
*/ | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@esri/arcgis-rest-request")):"function"==typeof define&&define.amd?define(["exports","@esri/arcgis-rest-request"],r):r(e.arcgisRest=e.arcgisRest||{},e.arcgisRest)}(this,function(e,r){"use strict";var t=Object.assign||function(e){for(var r,t=1,n=arguments.length;t<n;t++)for(var s in r=arguments[t])Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s]);return e};function n(e,t){var n=t.params?t:{params:t};return r.request(e,n).then(function(e){var r={token:e.access_token,username:e.username,expires:new Date(Date.now()+(60*e.expires_in*1e3-6e4)),ssl:!0===e.ssl};return e.refresh_token&&(r.refreshToken=e.refresh_token),r})}var s=function(){function e(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal="https://www.arcgis.com/sharing/rest"}return e.prototype.getToken=function(e,r){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):this._pendingTokenRequest?this._pendingTokenRequest:(this._pendingTokenRequest=this.refreshToken(r),this._pendingTokenRequest)},e.prototype.refreshToken=function(e){var r=this,s=t({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials"}},e);return n(this.portal+"/oauth2/token/",s).then(function(e){return r._pendingTokenRequest=null,r.token=e.token,r.expires=e.expires,e.token})},e.prototype.refreshSession=function(){var e=this;return this.refreshToken().then(function(){return e})},e}();function o(e,t){var n=t.params?t:{params:t};return"undefined"!=typeof window&&window.location&&window.location.host?n.params.referer=window.location.host:n.params.referer="@esri.arcgis-rest-auth",r.request(e,n)}var i=function(){function e(e){this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this.username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.refreshTokenTTL=e.refreshTokenTTL||1440,this.trustedServers={},this._pendingTokenRequests={}}return Object.defineProperty(e.prototype,"token",{get:function(){return this._token},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tokenExpires",{get:function(){return this._tokenExpires},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"refreshToken",{get:function(){return this._refreshToken},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"refreshTokenExpires",{get:function(){return this._refreshTokenExpires},enumerable:!0,configurable:!0}),e.beginOAuth2=function(n,s){void 0===s&&(s=window);var o,i=t({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",duration:20160,popup:!0,state:n.clientId,locale:""},n),a=i.portal,h=i.provider,p=i.clientId,u=i.duration,c=i.redirectUri,f=i.popup,k=i.state,l=i.locale;if(o="arcgis"===h?a+"/oauth2/authorize?client_id="+p+"&response_type=token&expiration="+u+"&redirect_uri="+encodeURIComponent(c)+"&state="+k+"&locale="+l:a+"/oauth2/social/authorize?client_id="+p+"&socialLoginProviderName="+h+"&autoAccountCreateForSocial=true&response_type=token&expiration="+u+"&redirect_uri="+encodeURIComponent(c)+"&state="+k+"&locale="+l,f){var d,T=((d={promise:null,resolve:null,reject:null}).promise=new Promise(function(e,r){d.resolve=e,d.reject=r}),d);return s["__ESRI_REST_AUTH_HANDLER_"+p]=function(t,n){if(t){var s=JSON.parse(t);T.reject(new r.ArcGISAuthError(s.errorMessage,s.error))}else if(n){var o=JSON.parse(n);T.resolve(new e({clientId:p,portal:a,ssl:o.ssl,token:o.token,tokenExpires:new Date(o.expires),username:o.username}))}},s.open(o,"oauth-window","height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes"),T.promise}s.location.href=o},e.completeOAuth2=function(n,s){void 0===s&&(s=window);var o=t({portal:"https://www.arcgis.com/sharing/rest"},n),i=o.portal,a=o.clientId;function h(t,n){if(s.opener&&s.opener.parent)return s.opener.parent["__ESRI_REST_AUTH_HANDLER_"+a](t?JSON.stringify(t):void 0,JSON.stringify(n)),void s.close();if(s!==s.parent)return s.parent["__ESRI_REST_AUTH_HANDLER_"+a](t?JSON.stringify(t):void 0,JSON.stringify(n)),void s.close();if(t)throw new r.ArcGISAuthError(t.errorMessage,t.error);return new e({clientId:a,portal:i,ssl:n.ssl,token:n.token,tokenExpires:n.expires,username:n.username})}var p=s.location.href.match(/access_token=(.+)&expires_in=(.+)&username=([^&]+)/);if(!p){var u=s.location.href.match(/error=(.+)&error_description=(.+)/);return h({error:u[1],errorMessage:decodeURIComponent(u[2])})}var c=p[1],f=new Date(Date.now()+1e3*parseInt(p[2],10)-6e4),k=decodeURIComponent(p[3]);return h(void 0,{token:c,expires:f,ssl:s.location.href.indexOf("&ssl=true")>-1||s.location.href.indexOf("#ssl=true")>-1,username:k})},e.authorize=function(e,r){var n=t({portal:"https://arcgis.com/sharing/rest",duration:20160},e),s=n.portal,o=n.clientId,i=n.duration,a=n.redirectUri;r.writeHead(301,{Location:s+"/oauth2/authorize?client_id="+o+"&duration="+i+"&response_type=code&redirect_uri="+encodeURIComponent(a)}),r.end()},e.exchangeAuthorizationCode=function(r,s){var o=t({portal:"https://www.arcgis.com/sharing/rest",refreshTokenTTL:1440},r),i=o.portal,a=o.clientId,h=o.redirectUri,p=o.refreshTokenTTL;return n(i+"/oauth2/token",{grant_type:"authorization_code",client_id:a,redirect_uri:h,code:s}).then(function(r){return new e({clientId:a,portal:i,ssl:r.ssl,redirectUri:h,refreshToken:r.refreshToken,refreshTokenTTL:p,refreshTokenExpires:new Date(Date.now()+1e3*(p-1)),token:r.token,tokenExpires:r.expires,username:r.username})})},e.deserialize=function(r){var t=JSON.parse(r);return new e({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:new Date(t.refreshTokenExpires),username:t.username,password:t.password,token:t.token,tokenExpires:new Date(t.tokenExpires),portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,refreshTokenTTL:t.refreshTokenTTL})},e.fromCredential=function(r){return new e({portal:r.server+"/sharing/rest",ssl:r.ssl,token:r.token,username:r.userId,tokenExpires:new Date(r.expires)})},e.prototype.toCredential=function(){return{expires:this.tokenExpires.getTime(),server:this.portal,ssl:this.ssl,token:this.token,userId:this.username}},e.prototype.getUser=function(e){var n=this;if(this._user&&this._user.username===this.username)return Promise.resolve(this._user);var s=this.portal+"/community/users/"+encodeURIComponent(this.username),o=t({httpMethod:"GET",authentication:this},e);return r.request(s,o).then(function(e){return n._user=e,e})},e.prototype.getToken=function(e,r){return/^https?:\/\/\S+\.arcgis\.com\/sharing\/rest/.test(this.portal)&&/^https?:\/\/\S+\.arcgis\.com.+/.test(e)?this.getFreshToken(r):new RegExp(this.portal).test(e)?this.getFreshToken(r):this.getTokenForServer(e,r)},e.prototype.toJSON=function(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,refreshTokenTTL:this.refreshTokenTTL}},e.prototype.serialize=function(){return JSON.stringify(this)},e.prototype.refreshSession=function(e){return this.username&&this.password?this.refreshWithUsernameAndPassword(e):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new r.ArcGISAuthError("Unable to refresh token."))},e.prototype.getTokenForServer=function(e,t){var n=this,s=e.split(/\/rest(\/admin)?\/services\//)[0],i=this.trustedServers[s];return i&&i.expires.getTime()>Date.now()?Promise.resolve(i.token):this._pendingTokenRequests[s]?this._pendingTokenRequests[s]:(this._pendingTokenRequests[s]=r.request(s+"/rest/info").then(function(e){return e.owningSystemUrl}).then(function(s){if(!s||!new RegExp(s).test(n.portal))throw new r.ArcGISAuthError(e+" is not federated with "+n.portal+".","NOT_FEDERATED");return r.request(s+"/sharing/rest/info",t)}).then(function(e){return e.authInfo.tokenServicesUrl}).then(function(r){return n.token?o(r,{params:{token:n.token,serverUrl:e,expiration:n.tokenDuration}}):o(r,{params:{username:n.username,password:n.password,expiration:n.tokenDuration}}).then(function(e){return n._token=e.token,n._tokenExpires=new Date(e.expires),e})}).then(function(e){return n.trustedServers[s]={expires:new Date(e.expires),token:e.token},e.token}),this._pendingTokenRequests[s])},e.prototype.getFreshToken=function(e){var r=this;return this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshSession(e).then(function(e){return r._pendingTokenRequests[r.portal]=null,e.token})),this._pendingTokenRequests[this.portal])},e.prototype.refreshWithUsernameAndPassword=function(e){var r=this,n=t({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return o(this.portal+"/generateToken",n).then(function(e){return r._token=e.token,r._tokenExpires=new Date(e.expires),r})},e.prototype.refreshWithRefreshToken=function(e){var r=this;if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()<Date.now())return this.refreshRefreshToken(e);var s=t({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},e);return n(this.portal+"/oauth2/token",s).then(function(e){return r._token=e.token,r._tokenExpires=e.expires,r})},e.prototype.refreshRefreshToken=function(e){var r=this,s=t({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},e);return n(this.portal+"/oauth2/token",s).then(function(e){return r._token=e.token,r._tokenExpires=e.expires,r._refreshToken=e.refreshToken,r._refreshTokenExpires=new Date(Date.now()+60*(r.refreshTokenTTL-1)*1e3),r})},e}();e.ApplicationSession=s,e.UserSession=i,e.fetchToken=n,e.generateToken=o,Object.defineProperty(e,"__esModule",{value:!0})}); | ||
//# sourceMappingURL=auth.umd.min.js.map |
{ | ||
"name": "@esri/arcgis-rest-auth", | ||
"version": "1.13.1", | ||
"version": "1.13.2", | ||
"description": "Authentication helpers for @esri/arcgis-rest-*.", | ||
@@ -17,7 +17,7 @@ "main": "dist/node/index.js", | ||
}, | ||
"devDependencies": { | ||
"@esri/arcgis-rest-common-types": "^1.13.2", | ||
"@esri/arcgis-rest-request": "^1.13.2" | ||
}, | ||
"peerDependencies": { | ||
"@esri/arcgis-rest-common-types": "^1.11.0", | ||
"@esri/arcgis-rest-request": "^1.11.0" | ||
}, | ||
"devDependencies": { | ||
"@esri/arcgis-rest-common-types": "^1.13.1", | ||
@@ -32,3 +32,6 @@ "@esri/arcgis-rest-request": "^1.13.1" | ||
"build:umd": "rollup -c ../../umd-base-profile.js && rollup -c ../../umd-production-profile.js", | ||
"build:node": "tsc --module commonjs --outDir ./dist/node" | ||
"build:node": "tsc --module commonjs --outDir ./dist/node", | ||
"dev:esm": "tsc -w --module es2015 --outDir ./dist/esm --declaration", | ||
"dev:umd": "rollup -w -c ../../umd-base-profile.js", | ||
"dev:node": "tsc -w --module commonjs --outDir ./dist/node" | ||
}, | ||
@@ -35,0 +38,0 @@ "publishConfig": { |
[![npm version][npm-img]][npm-url] | ||
[![build status][travis-img]][travis-url] | ||
[![Coverage Status][coverage-img]][coverage-url] | ||
[![apache licensed](https://img.shields.io/badge/license-Apache-green.svg?style=flat-square)](https://raw.githubusercontent.com/Esri/arcgis-rest-js/master/LICENSE) | ||
@@ -9,2 +10,4 @@ | ||
[travis-url]: https://travis-ci.org/Esri/arcgis-rest-js | ||
[coverage-img]: https://coveralls.io/repos/github/Esri/arcgis-rest-js/badge.svg | ||
[coverage-url]: https://coveralls.io/github/Esri/arcgis-rest-js | ||
@@ -11,0 +14,0 @@ # @esri/arcgis-rest-auth |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
233725
68
2373