Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@esri/arcgis-rest-auth

Package Overview
Dependencies
Maintainers
14
Versions
118
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@esri/arcgis-rest-auth - npm Package Compare versions

Comparing version 1.0.3 to 1.1.0

dist/umd/arcgis-rest-auth.umd.min.js

2

dist/esm/UserSession.js

@@ -151,3 +151,3 @@ /* Copyright (c) 2017 Environmental Systems Research Institute, Inc.

}
var match = win.location.href.match(/access_token=(.+)&expires_in=(.+)&username=(.+)/);
var match = win.location.href.match(/access_token=(.+)&expires_in=(.+)&username=([^&]+)/);
if (!match) {

@@ -154,0 +154,0 @@ var errorMatch = win.location.href.match(/error=(.+)&error_description=(.+)/);

@@ -153,3 +153,3 @@ "use strict";

}
var match = win.location.href.match(/access_token=(.+)&expires_in=(.+)&username=(.+)/);
var match = win.location.href.match(/access_token=(.+)&expires_in=(.+)&username=([^&]+)/);
if (!match) {

@@ -156,0 +156,0 @@ var errorMatch = win.location.href.match(/error=(.+)&error_description=(.+)/);

@@ -1,2 +0,512 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.arcgisRest=e.arcgisRest||{})}(this,function(e){"use strict";var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};var r=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++){t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},n=function(){return function(e,t,r,n,o){void 0===e&&(e="UNKNOWN_ERROR"),void 0===t&&(t="UNKNOWN_ERROR_CODE"),this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:t+": "+e,this.originalMessage=e,this.code=t,this.response=r,this.url=n,this.options=o}}();n.prototype=Object.create(Error.prototype),n.prototype.constructor=n;var o=function(e){!function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(n,e);function n(t,r,n,o,s){void 0===t&&(t="AUTHENTICATION_ERROR"),void 0===r&&(r="AUTHENTICATION_ERROR_CODE");var i=e.call(this,t,r,n,o,s)||this;return i.name="ArcGISAuthError",i.message="AUTHENTICATION_ERROR_CODE"===r?t:r+": "+t,i}return n.prototype.retry=function(e,t){var n=this;void 0===t&&(t=3);var o=0,s=function(i,a){e(n.url,n.options).then(function(e){var t=r({},n.options,{authentication:e});return o+=1,h(n.url,t)}).then(function(e){i(e)}).catch(function(e){"ArcGISAuthError"===e.name&&o<t?s(i,a):"ArcGISAuthError"===e.name&&o>=t?a(n):a(e)})};return new Promise(function(e,t){s(e,t)})},n}(n);function s(e){return Object.keys(e).some(function(t){var r=e[t];if(!r)return!1;switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}})}function i(e){var t={};return Object.keys(e).forEach(function(r){var n=e[r];if(n){var o;switch(n.constructor.name){case"Array":o="Object"===n[0].constructor.name?JSON.stringify(n):n.join(",");break;case"Object":o=JSON.stringify(n);break;case"Date":o=n.valueOf();break;case"Function":o=null;break;case"Boolean":o=n+"";break;default:o=n}o&&(t[r]=o)}}),t}function a(e){var t=i(e);return Object.keys(t).map(function(e){return r=e,n=t[e],encodeURIComponent(r)+"="+encodeURIComponent(n);var r,n}).join("&")}function h(e,t){void 0===t&&(t={params:{f:"json"}});var h=r({httpMethod:"POST",fetch:fetch},t),c=[],u=[];if(h.fetch||(c.push("`fetch`"),u.push("`isomorphic-fetch`")),Promise||(c.push("`Promise`"),u.push("`es6-promise`")),FormData||(c.push("`FormData`"),u.push("`isomorphic-form-data`")),!h.fetch||!Promise||!FormData)throw new Error("`arcgis-rest-request` requires global variables for `fetch`, `Promise` and `FormData` to be present in the global scope. You are missing "+c.join(", ")+". We recommend installing the "+u.join(", ")+" modules at the root of your application to add these to the global scope. See http://bit.ly/2BXbqzq for more info.");h.fetch===fetch&&(h.fetch=fetch.bind(Function("return this")()));var p=h.httpMethod,f=h.authentication,k=r({f:"json"},t.params),d={method:p};return(f?f.getToken(e):Promise.resolve("")).then(function(t){return t.length&&(k.token=t),"GET"===p&&(e=e+"?"+a(k)),"POST"===p&&(d.body=function(e){var t=s(e),r=i(e);if(t){var n=new FormData;return Object.keys(r).forEach(function(e){n.append(e,r[e])}),n}return a(e)}(k)),s(k)||(d.headers=new Headers,d.headers.append("Content-Type","application/x-www-form-urlencoded")),h.fetch(e,d)}).then(function(e){switch(k.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();case"image":case"zip":return e.blob()}}).then(function(t){return"json"===k.f||"geojson"===k.f?function(e,t,r,s){if(e.code>=400){var i=e.message,a=e.code;throw new n(i,a,e,t,s)}if(e.error){var h=e.error,c=(i=h.message,a=h.code,h.messageCode),u=c||a||"UNKNOWN_ERROR_CODE";if(498===a||499===a||"GWM_0003"===c)throw new o(i,u,e,t,s);throw new n(i,u,e,t,s)}if("failed"===e.status){i=void 0,a="UNKNOWN_ERROR_CODE";try{i=JSON.parse(e.statusMessage).message,a=JSON.parse(e.statusMessage).code}catch(t){i=e.statusMessage}throw new n(i,a,e,t,s)}return e}(t,e,0,h):t})}var c;(u=c||(c={})).ArcGISRequestError="ArcGISRequestError",u.ArcGISAuthError="ArcGISAuthError";var u;function p(e,t){return h(e,{params:t}).then(function(e){var t={token:e.access_token,username:e.username,expires:new Date(Date.now()+(60*e.expires_in*1e3-6e4))};return e.refresh_token&&(t.refreshToken=e.refresh_token),t})}var f=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",this.duration=e.duration||20160}return e.prototype.getToken=function(e){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):this._pendingTokenRequest?this._pendingTokenRequest:(this._pendingTokenRequest=this.refreshToken(),this._pendingTokenRequest)},e.prototype.refreshToken=function(){var e=this;return p(this.portal+"/oauth2/token/",{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials"}).then(function(t){return e._pendingTokenRequest=null,e.token=t.token,e.expires=t.expires,t.token})},e.prototype.refreshSession=function(){var e=this;return this.refreshToken().then(function(){return e})},e}();function k(e,t){return"undefined"!=typeof window&&window.location&&window.location.host?t.referer=window.location.host:t.referer="@esri.arcgis-rest-auth",h(e,{params:t})}var d=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.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(t,n){void 0===n&&(n=window);var o=r({portal:"https://arcgis.com/sharing/rest",duration:20160,popup:!0},t),s=o.portal,i=o.clientId,a=o.duration,h=o.redirectUri,c=o.popup,u=s+"/oauth2/authorize?client_id="+i+"&response_type=token&expiration="+a+"&redirect_uri="+encodeURIComponent(h);if(c){var p=function(){var e={promise:null,resolve:null,reject:null};return e.promise=new Promise(function(t,r){e.resolve=t,e.reject=r}),e}();return n["__ESRI_REST_AUTH_HANDLER_"+i]=function(t,r){t?p.reject(t):p.resolve(new e({clientId:i,portal:s,token:r.token,tokenExpires:r.expires,username:r.username}))},n.open(u,"oauth-window","height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes"),p.promise}n.location.href=u},e.completeOAuth2=function(t,o){void 0===o&&(o=window);var s=r({portal:"https://arcgis.com/sharing/rest"},t),i=s.portal,a=s.clientId;function h(t,r){if(o.opener&&o.opener.parent)return o.opener.parent["__ESRI_REST_AUTH_HANDLER_"+a](t,r),void o.close();if(o!==o.parent)return o.parent["__ESRI_REST_AUTH_HANDLER_"+a](t,r),void o.close();if(t)throw t;return new e({clientId:a,portal:i,token:r.token,tokenExpires:r.expires,username:r.username})}var c=o.location.href.match(/access_token=(.+)&expires_in=(.+)&username=(.+)/);if(!c){var u=o.location.href.match(/error=(.+)&error_description=(.+)/),p=u[1],f=decodeURIComponent(u[2]);return h(new n(f,p),null)}return h(null,{token:c[1],expires:new Date(Date.now()+1e3*parseInt(c[2],10)-6e4),username:c[3]})},e.authorize=function(e,t){var n=r({portal:"https://arcgis.com/sharing/rest",duration:20160},e),o=n.portal,s=n.clientId,i=n.duration,a=n.redirectUri;t.writeHead(301,{Location:o+"/oauth2/authorize?client_id="+s+"&duration="+i+"&response_type=code&redirect_uri="+encodeURIComponent(a)}),t.end()},e.exchangeAuthorizationCode=function(t,n){var o=r({portal:"https://www.arcgis.com/sharing/rest",duration:20160,refreshTokenTTL:1440},t),s=o.portal,i=o.clientId,a=(o.duration,o.redirectUri),h=o.refreshTokenTTL;return p(s+"/oauth2/token",{grant_type:"authorization_code",client_id:i,redirect_uri:a,code:n}).then(function(t){return new e({clientId:i,portal:s,redirectUri:a,refreshToken:t.refreshToken,refreshTokenTTL:h,refreshTokenExpires:new Date(Date.now()+1e3*(h-1)),token:t.token,tokenExpires:t.expires,username:t.username})})},e.deserialize=function(t){var r=JSON.parse(t);return new e({clientId:r.clientId,refreshToken:r.refreshToken,refreshTokenExpires:new Date(r.refreshTokenExpires),username:r.username,password:r.password,token:r.token,tokenExpires:new Date(r.tokenExpires),portal:r.portal,tokenDuration:r.tokenDuration,redirectUri:r.redirectUri,refreshTokenTTL:r.refreshTokenTTL})},e.prototype.getToken=function(e){return"https://www.arcgis.com/sharing/rest"===this.portal&&/^https?:\/\/\S+\.arcgis\.com.+/.test(e)?this.getFreshToken():new RegExp(this.portal).test(e)?this.getFreshToken():this.getTokenForServer(e)},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,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,refreshTokenTTL:this.refreshTokenTTL}},e.prototype.serialize=function(){return JSON.stringify(this)},e.prototype.refreshSession=function(){return this.username&&this.password?this.refreshWithUsernameAndPassword():this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new o("Unable to refresh token."))},e.prototype.getTokenForServer=function(e){var t=this,r=e.split("/rest/services/")[0],n=this.trustedServers[r];return n&&n.expires.getTime()>Date.now()?Promise.resolve(n.token):this._pendingTokenRequests[r]?this._pendingTokenRequests[r]:(this._pendingTokenRequests[r]=h(r+"/rest/info").then(function(e){return e.owningSystemUrl}).then(function(r){if(!new RegExp(r).test(t.portal))throw new o(e+" is not federated with "+t.portal+".","NOT_FEDERATED");return h(r+"/sharing/rest/info")}).then(function(e){return e.authInfo.tokenServicesUrl}).then(function(r){return k(r,{token:t.token,serverUrl:e,expiration:t.tokenDuration})}).then(function(e){return t.trustedServers[r]={expires:new Date(e.expires),token:e.token},e.token}),this._pendingTokenRequests[r])},e.prototype.getFreshToken=function(){var e=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().then(function(t){return e._pendingTokenRequests[e.portal]=null,t.token})),this._pendingTokenRequests[this.portal])},e.prototype.refreshWithUsernameAndPassword=function(){var e=this;return k(this.portal+"/generateToken",{username:this.username,password:this.password,expiration:this.tokenDuration}).then(function(t){return e._token=t.token,e._tokenExpires=new Date(t.expires),e})},e.prototype.refreshWithRefreshToken=function(){var e=this;return this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()<Date.now()?this.refreshRefreshToken():p(this.portal+"/oauth2/token",{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}).then(function(t){return e._token=t.token,e._tokenExpires=t.expires,e})},e.prototype.refreshRefreshToken=function(){var e=this;return p(this.portal+"/oauth2/token",{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}).then(function(t){return e._token=t.token,e._tokenExpires=t.expires,e._refreshToken=t.refreshToken,e._refreshTokenExpires=new Date(Date.now()+60*(e.refreshTokenTTL-1)*1e3),e})},e}();e.ApplicationSession=f,e.UserSession=d,e.fetchToken=p,e.generateToken=k,Object.defineProperty(e,"__esModule",{value:!0})});
/* @esri/arcgis-rest-auth - v1.1.0 - Sat Mar 03 2018 17:36:19 GMT-0800 (PST)
* Copyright (c) 2018 Environmental Systems Research Institute, Inc.
* Apache-2.0 */
(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));
}(this, (function (exports,arcgisRestRequest) { 'use strict';
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
* Apache-2.0 */
function fetchToken(url, options) {
return arcgisRestRequest.request(url, {
params: 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))
};
if (response.refresh_token) {
r.refreshToken = response.refresh_token;
}
return r;
});
}
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
* Apache-2.0 */
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";
this.duration = options.duration || 20160;
}
ApplicationSession.prototype.getToken = function (url) {
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();
return this._pendingTokenRequest;
};
ApplicationSession.prototype.refreshToken = function () {
var _this = this;
return fetchToken(this.portal + "/oauth2/token/", {
client_id: this.clientId,
client_secret: this.clientSecret,
grant_type: "client_credentials"
}).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) 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.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
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;
};
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
* Apache-2.0 */
function generateToken(url, params) {
/* istanbul ignore else */
if (typeof window !== "undefined" &&
window.location &&
window.location.host) {
params.referer = window.location.host;
}
else {
params.referer = "@esri.arcgis-rest-auth";
}
return arcgisRestRequest.request(url, { params: params });
}
/* Copyright (c) 2017 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;
}
/**
* Used to manage the authentication of ArcGIS Online and ArcGIS Enterprise users
* in `request`. This class also includes several
* helper methods for authenticating users with OAuth 2.0 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.tokenDuration = options.tokenDuration || 20160;
this.redirectUri = options.redirectUri;
this.refreshTokenTTL = options.refreshTokenTTL || 1440;
this.trustedServers = {};
this._pendingTokenRequests = {};
}
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
*/
UserSession.beginOAuth2 = function (options,
/* istanbul ignore next */ win) {
/* istanbul ignore next */ if (win === void 0) { win = window; }
var _a = __assign({
portal: "https://arcgis.com/sharing/rest",
duration: 20160,
popup: true
}, options), portal = _a.portal, clientId = _a.clientId, duration = _a.duration, redirectUri = _a.redirectUri, popup = _a.popup;
var url = portal + "/oauth2/authorize?client_id=" + clientId + "&response_type=token&expiration=" + duration + "&redirect_uri=" + encodeURIComponent(redirectUri);
if (!popup) {
win.location.href = url;
return undefined;
}
var session = defer();
win["__ESRI_REST_AUTH_HANDLER_" + clientId] = function (error, oauthInfo) {
if (error) {
session.reject(error);
return;
}
session.resolve(new UserSession({
clientId: clientId,
portal: portal,
token: oauthInfo.token,
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
*/
UserSession.completeOAuth2 = function (options,
/* istanbul ignore next*/ win) {
/* istanbul ignore next*/ if (win === void 0) { win = window; }
var _a = __assign({ portal: "https://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, oauthInfo);
win.close();
return undefined;
}
if (win !== win.parent) {
win.parent["__ESRI_REST_AUTH_HANDLER_" + clientId](error, oauthInfo);
win.close();
return undefined;
}
if (error) {
throw error;
}
return new UserSession({
clientId: clientId,
portal: portal,
token: oauthInfo.token,
tokenExpires: oauthInfo.expires,
username: oauthInfo.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(new arcgisRestRequest.ArcGISRequestError(errorMessage, error), null);
}
var token = match[1];
var expires = new Date(Date.now() + parseInt(match[2], 10) * 1000 - 60 * 1000);
var username = match[3];
return completeSignIn(null, {
token: token,
expires: expires,
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",
duration: 20160,
refreshTokenTTL: 1440
}, options), portal = _a.portal, clientId = _a.clientId, duration = _a.duration, 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,
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: 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,
tokenDuration: options.tokenDuration,
redirectUri: options.redirectUri,
refreshTokenTTL: options.refreshTokenTTL
});
};
/**
* Gets a 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) {
if (this.portal === "https://www.arcgis.com/sharing/rest" &&
/^https?:\/\/\S+\.arcgis\.com.+/.test(url)) {
return this.getFreshToken();
}
else if (new RegExp(this.portal).test(url)) {
return this.getFreshToken();
}
else {
return this.getTokenForServer(url);
}
};
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,
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 () {
if (this.username && this.password) {
return this.refreshWithUsernameAndPassword();
}
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) {
var _this = this;
var root = url.split("/rest/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 bail out with an error
* since we know we wont be able to generate a token
*/
if (!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");
})
.then(function (response) {
return response.authInfo.tokenServicesUrl;
})
.then(function (tokenServicesUrl) {
return generateToken(tokenServicesUrl, {
token: _this.token,
serverUrl: url,
expiration: _this.tokenDuration
});
})
.then(function (response) {
_this.trustedServers[root] = {
expires: new Date(response.expires),
token: response.token
};
return response.token;
});
return this._pendingTokenRequests[root];
};
/**
* Returns an unexpired token for the current `portal`.
*/
UserSession.prototype.getFreshToken = function () {
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().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 () {
var _this = this;
return generateToken(this.portal + "/generateToken", {
username: this.username,
password: this.password,
expiration: this.tokenDuration
}).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 () {
var _this = this;
if (this.refreshToken &&
this.refreshTokenExpires &&
this.refreshTokenExpires.getTime() < Date.now()) {
return this.refreshRefreshToken();
}
return fetchToken(this.portal + "/oauth2/token", {
client_id: this.clientId,
refresh_token: this.refreshToken,
grant_type: "refresh_token"
}).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 () {
var _this = this;
return fetchToken(this.portal + "/oauth2/token", {
client_id: this.clientId,
refresh_token: this.refreshToken,
redirect_uri: this.redirectUri,
grant_type: "exchange_refresh_token"
}).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;
}());
exports.ApplicationSession = ApplicationSession;
exports.UserSession = UserSession;
exports.fetchToken = fetchToken;
exports.generateToken = generateToken;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=arcgis-rest-auth.umd.js.map
{
"name": "@esri/arcgis-rest-auth",
"version": "1.0.3",
"version": "1.1.0",
"description": "Authentication helpers for @esri/arcgis-rest-*.",

@@ -11,2 +11,5 @@ "main": "dist/node/index.js",

"license": "Apache-2.0",
"files": [
"dist/**"
],
"dependencies": {

@@ -16,6 +19,6 @@ "tslib": "^1.7.1"

"peerDependencies": {
"@esri/arcgis-rest-request": "^1.0.3"
"@esri/arcgis-rest-request": "^1.1.0"
},
"devDependencies": {
"@esri/arcgis-rest-request": "^1.0.3"
"@esri/arcgis-rest-request": "^1.1.0"
},

@@ -27,3 +30,3 @@ "scripts": {

"build:esm": "tsc --module es2015 --outDir ./dist/esm --declaration",
"build:umd": "rollup -c ../../rollup.config.umd.js",
"build:umd": "rollup -c ../../umd-base-profile.js && rollup -c ../../umd-production-profile.js",
"build:node": "tsc --module commonjs --outDir ./dist/node"

@@ -30,0 +33,0 @@ },

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc