@esri/arcgis-rest-auth 3.4.2 → 4.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.ultra.cache.json +1 -0
  2. package/CHANGELOG.md +110 -0
  3. package/README.md +5 -5
  4. package/dist/bundled/auth.esm.js +7 -0
  5. package/dist/bundled/auth.esm.js.map +1 -0
  6. package/dist/bundled/auth.esm.min.js +7 -0
  7. package/dist/bundled/auth.esm.min.js.map +1 -0
  8. package/dist/bundled/auth.umd.js +112 -0
  9. package/dist/bundled/auth.umd.js.map +1 -0
  10. package/dist/bundled/auth.umd.min.js +7 -0
  11. package/dist/bundled/auth.umd.min.js.map +1 -0
  12. package/dist/cjs/index.js +20 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/package.json +3 -0
  15. package/dist/esm/index.d.ts +4 -9
  16. package/dist/esm/index.js +1 -8
  17. package/dist/esm/index.js.map +1 -1
  18. package/dist/esm/package.json +3 -0
  19. package/package.json +44 -45
  20. package/src/index.ts +34 -0
  21. package/tsconfig.json +6 -0
  22. package/dist/esm/ApiKey.d.ts +0 -26
  23. package/dist/esm/ApiKey.js +0 -23
  24. package/dist/esm/ApiKey.js.map +0 -1
  25. package/dist/esm/ApplicationSession.d.ts +0 -60
  26. package/dist/esm/ApplicationSession.js +0 -59
  27. package/dist/esm/ApplicationSession.js.map +0 -1
  28. package/dist/esm/UserSession.d.ts +0 -496
  29. package/dist/esm/UserSession.js +0 -890
  30. package/dist/esm/UserSession.js.map +0 -1
  31. package/dist/esm/app-tokens.d.ts +0 -87
  32. package/dist/esm/app-tokens.js +0 -104
  33. package/dist/esm/app-tokens.js.map +0 -1
  34. package/dist/esm/authenticated-request-options.d.ts +0 -18
  35. package/dist/esm/authenticated-request-options.js +0 -3
  36. package/dist/esm/authenticated-request-options.js.map +0 -1
  37. package/dist/esm/federation-utils.d.ts +0 -5
  38. package/dist/esm/federation-utils.js +0 -59
  39. package/dist/esm/federation-utils.js.map +0 -1
  40. package/dist/esm/fetch-token.d.ts +0 -9
  41. package/dist/esm/fetch-token.js +0 -23
  42. package/dist/esm/fetch-token.js.map +0 -1
  43. package/dist/esm/generate-token.d.ts +0 -7
  44. package/dist/esm/generate-token.js +0 -17
  45. package/dist/esm/generate-token.js.map +0 -1
  46. package/dist/esm/validate-app-access.d.ts +0 -47
  47. package/dist/esm/validate-app-access.js +0 -52
  48. package/dist/esm/validate-app-access.js.map +0 -1
  49. package/dist/node/ApiKey.js +0 -26
  50. package/dist/node/ApiKey.js.map +0 -1
  51. package/dist/node/ApplicationSession.js +0 -62
  52. package/dist/node/ApplicationSession.js.map +0 -1
  53. package/dist/node/UserSession.js +0 -893
  54. package/dist/node/UserSession.js.map +0 -1
  55. package/dist/node/app-tokens.js +0 -109
  56. package/dist/node/app-tokens.js.map +0 -1
  57. package/dist/node/authenticated-request-options.js +0 -5
  58. package/dist/node/authenticated-request-options.js.map +0 -1
  59. package/dist/node/federation-utils.js +0 -67
  60. package/dist/node/federation-utils.js.map +0 -1
  61. package/dist/node/fetch-token.js +0 -27
  62. package/dist/node/fetch-token.js.map +0 -1
  63. package/dist/node/generate-token.js +0 -21
  64. package/dist/node/generate-token.js.map +0 -1
  65. package/dist/node/index.js +0 -14
  66. package/dist/node/index.js.map +0 -1
  67. package/dist/node/validate-app-access.js +0 -56
  68. package/dist/node/validate-app-access.js.map +0 -1
  69. package/dist/umd/auth.umd.js +0 -1253
  70. package/dist/umd/auth.umd.js.map +0 -1
  71. package/dist/umd/auth.umd.min.js +0 -7
  72. package/dist/umd/auth.umd.min.js.map +0 -1
@@ -1,890 +0,0 @@
1
- /* Copyright (c) 2017-2019 Environmental Systems Research Institute, Inc.
2
- * Apache-2.0 */
3
- import { __assign } from "tslib";
4
- import { request, ArcGISAuthError, cleanUrl, encodeQueryString, decodeQueryString, } from "@esri/arcgis-rest-request";
5
- import { generateToken } from "./generate-token";
6
- import { fetchToken } from "./fetch-token";
7
- import { canUseOnlineToken, isFederated } from "./federation-utils";
8
- import { validateAppAccess } from "./validate-app-access";
9
- function defer() {
10
- var deferred = {
11
- promise: null,
12
- resolve: null,
13
- reject: null,
14
- };
15
- deferred.promise = new Promise(function (resolve, reject) {
16
- deferred.resolve = resolve;
17
- deferred.reject = reject;
18
- });
19
- return deferred;
20
- }
21
- /**
22
- * ```js
23
- * import { UserSession } from '@esri/arcgis-rest-auth';
24
- * UserSession.beginOAuth2({
25
- * // register an app of your own to create a unique clientId
26
- * clientId: "abc123",
27
- * redirectUri: 'https://yourapp.com/authenticate.html'
28
- * })
29
- * .then(session)
30
- * // or
31
- * new UserSession({
32
- * username: "jsmith",
33
- * password: "123456"
34
- * })
35
- * // or
36
- * UserSession.deserialize(cache)
37
- * ```
38
- * 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.
39
- */
40
- var UserSession = /** @class */ (function () {
41
- function UserSession(options) {
42
- this.clientId = options.clientId;
43
- this._refreshToken = options.refreshToken;
44
- this._refreshTokenExpires = options.refreshTokenExpires;
45
- this.username = options.username;
46
- this.password = options.password;
47
- this._token = options.token;
48
- this._tokenExpires = options.tokenExpires;
49
- this.portal = options.portal
50
- ? cleanUrl(options.portal)
51
- : "https://www.arcgis.com/sharing/rest";
52
- this.ssl = options.ssl;
53
- this.provider = options.provider || "arcgis";
54
- this.tokenDuration = options.tokenDuration || 20160;
55
- this.redirectUri = options.redirectUri;
56
- this.refreshTokenTTL = options.refreshTokenTTL || 20160;
57
- this.server = options.server;
58
- this.federatedServers = {};
59
- this.trustedDomains = [];
60
- // if a non-federated server was passed explicitly, it should be trusted.
61
- if (options.server) {
62
- // if the url includes more than '/arcgis/', trim the rest
63
- var root = this.getServerRootUrl(options.server);
64
- this.federatedServers[root] = {
65
- token: options.token,
66
- expires: options.tokenExpires,
67
- };
68
- }
69
- this._pendingTokenRequests = {};
70
- }
71
- Object.defineProperty(UserSession.prototype, "token", {
72
- /**
73
- * The current ArcGIS Online or ArcGIS Enterprise `token`.
74
- */
75
- get: function () {
76
- return this._token;
77
- },
78
- enumerable: false,
79
- configurable: true
80
- });
81
- Object.defineProperty(UserSession.prototype, "tokenExpires", {
82
- /**
83
- * The expiration time of the current `token`.
84
- */
85
- get: function () {
86
- return this._tokenExpires;
87
- },
88
- enumerable: false,
89
- configurable: true
90
- });
91
- Object.defineProperty(UserSession.prototype, "refreshToken", {
92
- /**
93
- * The current token to ArcGIS Online or ArcGIS Enterprise.
94
- */
95
- get: function () {
96
- return this._refreshToken;
97
- },
98
- enumerable: false,
99
- configurable: true
100
- });
101
- Object.defineProperty(UserSession.prototype, "refreshTokenExpires", {
102
- /**
103
- * The expiration time of the current `refreshToken`.
104
- */
105
- get: function () {
106
- return this._refreshTokenExpires;
107
- },
108
- enumerable: false,
109
- configurable: true
110
- });
111
- Object.defineProperty(UserSession.prototype, "trustedServers", {
112
- /**
113
- * Deprecated, use `federatedServers` instead.
114
- *
115
- * @deprecated
116
- */
117
- get: function () {
118
- console.log("DEPRECATED: use federatedServers instead");
119
- return this.federatedServers;
120
- },
121
- enumerable: false,
122
- configurable: true
123
- });
124
- /**
125
- * Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is `true` the
126
- * authentication window will open in a new tab/window and the function will return
127
- * Promise<UserSession>. Otherwise, the user will be redirected to the
128
- * authorization page in their current tab/window and the function will return `undefined`.
129
- *
130
- * @browserOnly
131
- */
132
- /* istanbul ignore next */
133
- UserSession.beginOAuth2 = function (options, win) {
134
- if (win === void 0) { win = window; }
135
- if (options.duration) {
136
- console.log("DEPRECATED: 'duration' is deprecated - use 'expiration' instead");
137
- }
138
- var _a = __assign({
139
- portal: "https://www.arcgis.com/sharing/rest",
140
- provider: "arcgis",
141
- expiration: 20160,
142
- popup: true,
143
- popupWindowFeatures: "height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",
144
- state: options.clientId,
145
- locale: "",
146
- }, options), portal = _a.portal, provider = _a.provider, clientId = _a.clientId, expiration = _a.expiration, redirectUri = _a.redirectUri, popup = _a.popup, popupWindowFeatures = _a.popupWindowFeatures, state = _a.state, locale = _a.locale, params = _a.params;
147
- var url;
148
- if (provider === "arcgis") {
149
- url = portal + "/oauth2/authorize?client_id=" + clientId + "&response_type=token&expiration=" + (options.duration || expiration) + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&state=" + state + "&locale=" + locale;
150
- }
151
- else {
152
- url = portal + "/oauth2/social/authorize?client_id=" + clientId + "&socialLoginProviderName=" + provider + "&autoAccountCreateForSocial=true&response_type=token&expiration=" + (options.duration || expiration) + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&state=" + state + "&locale=" + locale;
153
- }
154
- // append additional params
155
- if (params) {
156
- url = url + "&" + encodeQueryString(params);
157
- }
158
- if (!popup) {
159
- win.location.href = url;
160
- return undefined;
161
- }
162
- var session = defer();
163
- win["__ESRI_REST_AUTH_HANDLER_" + clientId] = function (errorString, oauthInfoString) {
164
- if (errorString) {
165
- var error = JSON.parse(errorString);
166
- session.reject(new ArcGISAuthError(error.errorMessage, error.error));
167
- return;
168
- }
169
- if (oauthInfoString) {
170
- var oauthInfo = JSON.parse(oauthInfoString);
171
- session.resolve(new UserSession({
172
- clientId: clientId,
173
- portal: portal,
174
- ssl: oauthInfo.ssl,
175
- token: oauthInfo.token,
176
- tokenExpires: new Date(oauthInfo.expires),
177
- username: oauthInfo.username,
178
- }));
179
- }
180
- };
181
- win.open(url, "oauth-window", popupWindowFeatures);
182
- return session.promise;
183
- };
184
- /**
185
- * Completes a browser-based OAuth 2.0 sign in. If `options.popup` is `true` the user
186
- * will be returned to the previous window. Otherwise a new `UserSession`
187
- * will be returned. You must pass the same values for `options.popup` and
188
- * `options.portal` as you used in `beginOAuth2()`.
189
- *
190
- * @browserOnly
191
- */
192
- /* istanbul ignore next */
193
- UserSession.completeOAuth2 = function (options, win) {
194
- if (win === void 0) { win = window; }
195
- var _a = __assign({ portal: "https://www.arcgis.com/sharing/rest", popup: true }, options), portal = _a.portal, clientId = _a.clientId, popup = _a.popup;
196
- function completeSignIn(error, oauthInfo) {
197
- try {
198
- var handlerFn = void 0;
199
- var handlerFnName = "__ESRI_REST_AUTH_HANDLER_" + clientId;
200
- if (popup) {
201
- // Guard b/c IE does not support window.opener
202
- if (win.opener) {
203
- if (win.opener.parent && win.opener.parent[handlerFnName]) {
204
- handlerFn = win.opener.parent[handlerFnName];
205
- }
206
- else if (win.opener && win.opener[handlerFnName]) {
207
- // support pop-out oauth from within an iframe
208
- handlerFn = win.opener[handlerFnName];
209
- }
210
- }
211
- else {
212
- // IE
213
- if (win !== win.parent && win.parent && win.parent[handlerFnName]) {
214
- handlerFn = win.parent[handlerFnName];
215
- }
216
- }
217
- // if we have a handler fn, call it and close the window
218
- if (handlerFn) {
219
- handlerFn(error ? JSON.stringify(error) : undefined, JSON.stringify(oauthInfo));
220
- win.close();
221
- return undefined;
222
- }
223
- }
224
- }
225
- catch (e) {
226
- throw new ArcGISAuthError("Unable to complete authentication. It's possible you specified popup based oAuth2 but no handler from \"beginOAuth2()\" present. This generally happens because the \"popup\" option differs between \"beginOAuth2()\" and \"completeOAuth2()\".");
227
- }
228
- if (error) {
229
- throw new ArcGISAuthError(error.errorMessage, error.error);
230
- }
231
- return new UserSession({
232
- clientId: clientId,
233
- portal: portal,
234
- ssl: oauthInfo.ssl,
235
- token: oauthInfo.token,
236
- tokenExpires: oauthInfo.expires,
237
- username: oauthInfo.username,
238
- });
239
- }
240
- var params = decodeQueryString(win.location.hash);
241
- if (!params.access_token) {
242
- var error = void 0;
243
- var errorMessage = "Unknown error";
244
- if (params.error) {
245
- error = params.error;
246
- errorMessage = params.error_description;
247
- }
248
- return completeSignIn({ error: error, errorMessage: errorMessage });
249
- }
250
- var token = params.access_token;
251
- var expires = new Date(Date.now() + parseInt(params.expires_in, 10) * 1000 - 60 * 1000);
252
- var username = params.username;
253
- var ssl = params.ssl === "true";
254
- return completeSignIn(undefined, {
255
- token: token,
256
- expires: expires,
257
- ssl: ssl,
258
- username: username,
259
- });
260
- };
261
- /**
262
- * Request session information from the parent application
263
- *
264
- * When an application is embedded into another application via an IFrame, the embedded app can
265
- * use `window.postMessage` to request credentials from the host application. This function wraps
266
- * that behavior.
267
- *
268
- * The ArcGIS API for Javascript has this built into the Identity Manager as of the 4.19 release.
269
- *
270
- * Note: The parent application will not respond if the embedded app's origin is not:
271
- * - the same origin as the parent or *.arcgis.com (JSAPI)
272
- * - in the list of valid child origins (REST-JS)
273
- *
274
- *
275
- * @param parentOrigin origin of the parent frame. Passed into the embedded application as `parentOrigin` query param
276
- * @browserOnly
277
- */
278
- UserSession.fromParent = function (parentOrigin, win) {
279
- /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */
280
- if (!win && window) {
281
- win = window;
282
- }
283
- // Declare handler outside of promise scope so we can detach it
284
- var handler;
285
- // return a promise that will resolve when the handler receives
286
- // session information from the correct origin
287
- return new Promise(function (resolve, reject) {
288
- // create an event handler that just wraps the parentMessageHandler
289
- handler = function (event) {
290
- // ensure we only listen to events from the parent
291
- if (event.source === win.parent && event.data) {
292
- try {
293
- return resolve(UserSession.parentMessageHandler(event));
294
- }
295
- catch (err) {
296
- return reject(err);
297
- }
298
- }
299
- };
300
- // add listener
301
- win.addEventListener("message", handler, false);
302
- win.parent.postMessage({ type: "arcgis:auth:requestCredential" }, parentOrigin);
303
- }).then(function (session) {
304
- win.removeEventListener("message", handler, false);
305
- return session;
306
- });
307
- };
308
- /**
309
- * Begins a new server-based OAuth 2.0 sign in. This will redirect the user to
310
- * the ArcGIS Online or ArcGIS Enterprise authorization page.
311
- *
312
- * @nodeOnly
313
- */
314
- UserSession.authorize = function (options, response) {
315
- if (options.duration) {
316
- console.log("DEPRECATED: 'duration' is deprecated - use 'expiration' instead");
317
- }
318
- var _a = __assign({ portal: "https://arcgis.com/sharing/rest", expiration: 20160 }, options), portal = _a.portal, clientId = _a.clientId, expiration = _a.expiration, redirectUri = _a.redirectUri;
319
- response.writeHead(301, {
320
- Location: portal + "/oauth2/authorize?client_id=" + clientId + "&expiration=" + (options.duration || expiration) + "&response_type=code&redirect_uri=" + encodeURIComponent(redirectUri),
321
- });
322
- response.end();
323
- };
324
- /**
325
- * Completes the server-based OAuth 2.0 sign in process by exchanging the `authorizationCode`
326
- * for a `access_token`.
327
- *
328
- * @nodeOnly
329
- */
330
- UserSession.exchangeAuthorizationCode = function (options, authorizationCode) {
331
- var _a = __assign({
332
- portal: "https://www.arcgis.com/sharing/rest",
333
- refreshTokenTTL: 20160,
334
- }, options), portal = _a.portal, clientId = _a.clientId, redirectUri = _a.redirectUri, refreshTokenTTL = _a.refreshTokenTTL;
335
- return fetchToken(portal + "/oauth2/token", {
336
- params: {
337
- grant_type: "authorization_code",
338
- client_id: clientId,
339
- redirect_uri: redirectUri,
340
- code: authorizationCode,
341
- },
342
- }).then(function (response) {
343
- return new UserSession({
344
- clientId: clientId,
345
- portal: portal,
346
- ssl: response.ssl,
347
- redirectUri: redirectUri,
348
- refreshToken: response.refreshToken,
349
- refreshTokenTTL: refreshTokenTTL,
350
- refreshTokenExpires: new Date(Date.now() + (refreshTokenTTL - 1) * 60 * 1000),
351
- token: response.token,
352
- tokenExpires: response.expires,
353
- username: response.username,
354
- });
355
- });
356
- };
357
- UserSession.deserialize = function (str) {
358
- var options = JSON.parse(str);
359
- return new UserSession({
360
- clientId: options.clientId,
361
- refreshToken: options.refreshToken,
362
- refreshTokenExpires: new Date(options.refreshTokenExpires),
363
- username: options.username,
364
- password: options.password,
365
- token: options.token,
366
- tokenExpires: new Date(options.tokenExpires),
367
- portal: options.portal,
368
- ssl: options.ssl,
369
- tokenDuration: options.tokenDuration,
370
- redirectUri: options.redirectUri,
371
- refreshTokenTTL: options.refreshTokenTTL,
372
- });
373
- };
374
- /**
375
- * Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).
376
- *
377
- * ```js
378
- * UserSession.fromCredential({
379
- * userId: "jsmith",
380
- * token: "secret"
381
- * });
382
- * ```
383
- *
384
- * @returns UserSession
385
- */
386
- UserSession.fromCredential = function (credential) {
387
- // At ArcGIS Online 9.1, credentials no longer include the ssl and expires properties
388
- // Here, we provide default values for them to cover this condition
389
- var ssl = typeof credential.ssl !== "undefined" ? credential.ssl : true;
390
- var expires = credential.expires || Date.now() + 7200000 /* 2 hours */;
391
- return new UserSession({
392
- portal: credential.server.includes("sharing/rest")
393
- ? credential.server
394
- : credential.server + "/sharing/rest",
395
- ssl: ssl,
396
- token: credential.token,
397
- username: credential.userId,
398
- tokenExpires: new Date(expires),
399
- });
400
- };
401
- /**
402
- * Handle the response from the parent
403
- * @param event DOM Event
404
- */
405
- UserSession.parentMessageHandler = function (event) {
406
- if (event.data.type === "arcgis:auth:credential") {
407
- return UserSession.fromCredential(event.data.credential);
408
- }
409
- if (event.data.type === "arcgis:auth:error") {
410
- var err = new Error(event.data.error.message);
411
- err.name = event.data.error.name;
412
- throw err;
413
- }
414
- else {
415
- throw new Error("Unknown message type.");
416
- }
417
- };
418
- /**
419
- * Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).
420
- *
421
- * ```js
422
- * esriId.registerToken(session.toCredential());
423
- * ```
424
- *
425
- * @returns ICredential
426
- */
427
- UserSession.prototype.toCredential = function () {
428
- return {
429
- expires: this.tokenExpires.getTime(),
430
- server: this.portal,
431
- ssl: this.ssl,
432
- token: this.token,
433
- userId: this.username,
434
- };
435
- };
436
- /**
437
- * 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.
438
- *
439
- * ```js
440
- * session.getUser()
441
- * .then(response => {
442
- * console.log(response.role); // "org_admin"
443
- * })
444
- * ```
445
- *
446
- * @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.
447
- * @returns A Promise that will resolve with the data from the response.
448
- */
449
- UserSession.prototype.getUser = function (requestOptions) {
450
- var _this = this;
451
- if (this._pendingUserRequest) {
452
- return this._pendingUserRequest;
453
- }
454
- else if (this._user) {
455
- return Promise.resolve(this._user);
456
- }
457
- else {
458
- var url = this.portal + "/community/self";
459
- var options = __assign(__assign({ httpMethod: "GET", authentication: this }, requestOptions), { rawResponse: false });
460
- this._pendingUserRequest = request(url, options).then(function (response) {
461
- _this._user = response;
462
- _this._pendingUserRequest = null;
463
- return response;
464
- });
465
- return this._pendingUserRequest;
466
- }
467
- };
468
- /**
469
- * Returns information about the currently logged in user's [portal](https://developers.arcgis.com/rest/users-groups-and-items/portal-self.htm). Subsequent calls will *not* result in additional web traffic.
470
- *
471
- * ```js
472
- * session.getPortal()
473
- * .then(response => {
474
- * console.log(portal.name); // "City of ..."
475
- * })
476
- * ```
477
- *
478
- * @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.
479
- * @returns A Promise that will resolve with the data from the response.
480
- */
481
- UserSession.prototype.getPortal = function (requestOptions) {
482
- var _this = this;
483
- if (this._pendingPortalRequest) {
484
- return this._pendingPortalRequest;
485
- }
486
- else if (this._portalInfo) {
487
- return Promise.resolve(this._portalInfo);
488
- }
489
- else {
490
- var url = this.portal + "/portals/self";
491
- var options = __assign(__assign({ httpMethod: "GET", authentication: this }, requestOptions), { rawResponse: false });
492
- this._pendingPortalRequest = request(url, options).then(function (response) {
493
- _this._portalInfo = response;
494
- _this._pendingPortalRequest = null;
495
- return response;
496
- });
497
- return this._pendingPortalRequest;
498
- }
499
- };
500
- /**
501
- * Returns the username for 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. This is also used internally when a username is required for some requests but is not present in the options.
502
- *
503
- * * ```js
504
- * session.getUsername()
505
- * .then(response => {
506
- * console.log(response); // "casey_jones"
507
- * })
508
- * ```
509
- */
510
- UserSession.prototype.getUsername = function () {
511
- if (this.username) {
512
- return Promise.resolve(this.username);
513
- }
514
- else if (this._user) {
515
- return Promise.resolve(this._user.username);
516
- }
517
- else {
518
- return this.getUser().then(function (user) {
519
- return user.username;
520
- });
521
- }
522
- };
523
- /**
524
- * Gets an appropriate token for the given URL. If `portal` is ArcGIS Online and
525
- * the request is to an ArcGIS Online domain `token` will be used. If the request
526
- * is to the current `portal` the current `token` will also be used. However if
527
- * the request is to an unknown server we will validate the server with a request
528
- * to our current `portal`.
529
- */
530
- UserSession.prototype.getToken = function (url, requestOptions) {
531
- if (canUseOnlineToken(this.portal, url)) {
532
- return this.getFreshToken(requestOptions);
533
- }
534
- else if (new RegExp(this.portal, "i").test(url)) {
535
- return this.getFreshToken(requestOptions);
536
- }
537
- else {
538
- return this.getTokenForServer(url, requestOptions);
539
- }
540
- };
541
- /**
542
- * Get application access information for the current user
543
- * see `validateAppAccess` function for details
544
- *
545
- * @param clientId application client id
546
- */
547
- UserSession.prototype.validateAppAccess = function (clientId) {
548
- return this.getToken(this.portal).then(function (token) {
549
- return validateAppAccess(token, clientId);
550
- });
551
- };
552
- UserSession.prototype.toJSON = function () {
553
- return {
554
- clientId: this.clientId,
555
- refreshToken: this.refreshToken,
556
- refreshTokenExpires: this.refreshTokenExpires,
557
- username: this.username,
558
- password: this.password,
559
- token: this.token,
560
- tokenExpires: this.tokenExpires,
561
- portal: this.portal,
562
- ssl: this.ssl,
563
- tokenDuration: this.tokenDuration,
564
- redirectUri: this.redirectUri,
565
- refreshTokenTTL: this.refreshTokenTTL,
566
- };
567
- };
568
- UserSession.prototype.serialize = function () {
569
- return JSON.stringify(this);
570
- };
571
- /**
572
- * For a "Host" app that embeds other platform apps via iframes, after authenticating the user
573
- * and creating a UserSession, the app can then enable "post message" style authentication by calling
574
- * this method.
575
- *
576
- * Internally this adds an event listener on window for the `message` event
577
- *
578
- * @param validChildOrigins Array of origins that are allowed to request authentication from the host app
579
- */
580
- UserSession.prototype.enablePostMessageAuth = function (validChildOrigins, win) {
581
- /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */
582
- if (!win && window) {
583
- win = window;
584
- }
585
- this._hostHandler = this.createPostMessageHandler(validChildOrigins);
586
- win.addEventListener("message", this._hostHandler, false);
587
- };
588
- /**
589
- * For a "Host" app that has embedded other platform apps via iframes, when the host needs
590
- * to transition routes, it should call `UserSession.disablePostMessageAuth()` to remove
591
- * the event listener and prevent memory leaks
592
- */
593
- UserSession.prototype.disablePostMessageAuth = function (win) {
594
- /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */
595
- if (!win && window) {
596
- win = window;
597
- }
598
- win.removeEventListener("message", this._hostHandler, false);
599
- };
600
- /**
601
- * Manually refreshes the current `token` and `tokenExpires`.
602
- */
603
- UserSession.prototype.refreshSession = function (requestOptions) {
604
- // make sure subsequent calls to getUser() don't returned cached metadata
605
- this._user = null;
606
- if (this.username && this.password) {
607
- return this.refreshWithUsernameAndPassword(requestOptions);
608
- }
609
- if (this.clientId && this.refreshToken) {
610
- return this.refreshWithRefreshToken();
611
- }
612
- return Promise.reject(new ArcGISAuthError("Unable to refresh token."));
613
- };
614
- /**
615
- * Determines the root of the ArcGIS Server or Portal for a given URL.
616
- *
617
- * @param url the URl to determine the root url for.
618
- */
619
- UserSession.prototype.getServerRootUrl = function (url) {
620
- var root = cleanUrl(url).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/)[0];
621
- var _a = root.match(/(https?:\/\/)(.+)/), match = _a[0], protocol = _a[1], domainAndPath = _a[2];
622
- var _b = domainAndPath.split("/"), domain = _b[0], path = _b.slice(1);
623
- // only the domain is lowercased because in some cases an org id might be
624
- // in the path which cannot be lowercased.
625
- return "" + protocol + domain.toLowerCase() + "/" + path.join("/");
626
- };
627
- /**
628
- * Returns the proper [`credentials`] option for `fetch` for a given domain.
629
- * See [trusted server](https://enterprise.arcgis.com/en/portal/latest/administer/windows/configure-security.htm#ESRI_SECTION1_70CC159B3540440AB325BE5D89DBE94A).
630
- * Used internally by underlying request methods to add support for specific security considerations.
631
- *
632
- * @param url The url of the request
633
- * @returns "include" or "same-origin"
634
- */
635
- UserSession.prototype.getDomainCredentials = function (url) {
636
- if (!this.trustedDomains || !this.trustedDomains.length) {
637
- return "same-origin";
638
- }
639
- return this.trustedDomains.some(function (domainWithProtocol) {
640
- return url.startsWith(domainWithProtocol);
641
- })
642
- ? "include"
643
- : "same-origin";
644
- };
645
- /**
646
- * Return a function that closes over the validOrigins array and
647
- * can be used as an event handler for the `message` event
648
- *
649
- * @param validOrigins Array of valid origins
650
- */
651
- UserSession.prototype.createPostMessageHandler = function (validOrigins) {
652
- var _this = this;
653
- // return a function that closes over the validOrigins and
654
- // has access to the credential
655
- return function (event) {
656
- // Verify that the origin is valid
657
- // Note: do not use regex's here. validOrigins is an array so we're checking that the event's origin
658
- // is in the array via exact match. More info about avoiding postMessage xss issues here
659
- // https://jlajara.gitlab.io/web/2020/07/17/Dom_XSS_PostMessage_2.html#tipsbypasses-in-postmessage-vulnerabilities
660
- var isValidOrigin = validOrigins.indexOf(event.origin) > -1;
661
- // JSAPI handles this slightly differently - instead of checking a list, it will respond if
662
- // event.origin === window.location.origin || event.origin.endsWith('.arcgis.com')
663
- // For Hub, and to enable cross domain debugging with port's in urls, we are opting to
664
- // use a list of valid origins
665
- // Ensure the message type is something we want to handle
666
- var isValidType = event.data.type === "arcgis:auth:requestCredential";
667
- if (isValidOrigin && isValidType) {
668
- var credential = _this.toCredential();
669
- // the following line allows us to conform to our spec without changing other depended-on functionality
670
- // https://github.com/Esri/arcgis-rest-js/blob/master/packages/arcgis-rest-auth/post-message-auth-spec.md#arcgisauthcredential
671
- credential.server = credential.server.replace("/sharing/rest", "");
672
- event.source.postMessage({
673
- type: "arcgis:auth:credential",
674
- credential: credential,
675
- }, event.origin);
676
- }
677
- };
678
- };
679
- /**
680
- * Validates that a given URL is properly federated with our current `portal`.
681
- * Attempts to use the internal `federatedServers` cache first.
682
- */
683
- UserSession.prototype.getTokenForServer = function (url, requestOptions) {
684
- var _this = this;
685
- // requests to /rest/services/ and /rest/admin/services/ are both valid
686
- // Federated servers may have inconsistent casing, so lowerCase it
687
- var root = this.getServerRootUrl(url);
688
- var existingToken = this.federatedServers[root];
689
- if (existingToken &&
690
- existingToken.expires &&
691
- existingToken.expires.getTime() > Date.now()) {
692
- return Promise.resolve(existingToken.token);
693
- }
694
- if (this._pendingTokenRequests[root]) {
695
- return this._pendingTokenRequests[root];
696
- }
697
- this._pendingTokenRequests[root] = this.fetchAuthorizedDomains().then(function () {
698
- return request(root + "/rest/info", {
699
- credentials: _this.getDomainCredentials(url),
700
- })
701
- .then(function (response) {
702
- if (response.owningSystemUrl) {
703
- /**
704
- * if this server is not owned by this portal
705
- * bail out with an error since we know we wont
706
- * be able to generate a token
707
- */
708
- if (!isFederated(response.owningSystemUrl, _this.portal)) {
709
- throw new ArcGISAuthError(url + " is not federated with " + _this.portal + ".", "NOT_FEDERATED");
710
- }
711
- else {
712
- /**
713
- * if the server is federated, use the relevant token endpoint.
714
- */
715
- return request(response.owningSystemUrl + "/sharing/rest/info", requestOptions);
716
- }
717
- }
718
- else if (response.authInfo &&
719
- _this.federatedServers[root] !== undefined) {
720
- /**
721
- * if its a stand-alone instance of ArcGIS Server that doesn't advertise
722
- * federation, but the root server url is recognized, use its built in token endpoint.
723
- */
724
- return Promise.resolve({
725
- authInfo: response.authInfo,
726
- });
727
- }
728
- else {
729
- throw new ArcGISAuthError(url + " is not federated with any portal and is not explicitly trusted.", "NOT_FEDERATED");
730
- }
731
- })
732
- .then(function (response) {
733
- return response.authInfo.tokenServicesUrl;
734
- })
735
- .then(function (tokenServicesUrl) {
736
- // an expired token cant be used to generate a new token
737
- if (_this.token && _this.tokenExpires.getTime() > Date.now()) {
738
- return generateToken(tokenServicesUrl, {
739
- params: {
740
- token: _this.token,
741
- serverUrl: url,
742
- expiration: _this.tokenDuration,
743
- client: "referer",
744
- },
745
- });
746
- // generate an entirely fresh token if necessary
747
- }
748
- else {
749
- return generateToken(tokenServicesUrl, {
750
- params: {
751
- username: _this.username,
752
- password: _this.password,
753
- expiration: _this.tokenDuration,
754
- client: "referer",
755
- },
756
- }).then(function (response) {
757
- _this._token = response.token;
758
- _this._tokenExpires = new Date(response.expires);
759
- return response;
760
- });
761
- }
762
- })
763
- .then(function (response) {
764
- _this.federatedServers[root] = {
765
- expires: new Date(response.expires),
766
- token: response.token,
767
- };
768
- delete _this._pendingTokenRequests[root];
769
- return response.token;
770
- });
771
- });
772
- return this._pendingTokenRequests[root];
773
- };
774
- /**
775
- * Returns an unexpired token for the current `portal`.
776
- */
777
- UserSession.prototype.getFreshToken = function (requestOptions) {
778
- var _this = this;
779
- if (this.token && !this.tokenExpires) {
780
- return Promise.resolve(this.token);
781
- }
782
- if (this.token &&
783
- this.tokenExpires &&
784
- this.tokenExpires.getTime() > Date.now()) {
785
- return Promise.resolve(this.token);
786
- }
787
- if (!this._pendingTokenRequests[this.portal]) {
788
- this._pendingTokenRequests[this.portal] = this.refreshSession(requestOptions).then(function (session) {
789
- _this._pendingTokenRequests[_this.portal] = null;
790
- return session.token;
791
- });
792
- }
793
- return this._pendingTokenRequests[this.portal];
794
- };
795
- /**
796
- * Refreshes the current `token` and `tokenExpires` with `username` and
797
- * `password`.
798
- */
799
- UserSession.prototype.refreshWithUsernameAndPassword = function (requestOptions) {
800
- var _this = this;
801
- var options = __assign({ params: {
802
- username: this.username,
803
- password: this.password,
804
- expiration: this.tokenDuration,
805
- } }, requestOptions);
806
- return generateToken(this.portal + "/generateToken", options).then(function (response) {
807
- _this._token = response.token;
808
- _this._tokenExpires = new Date(response.expires);
809
- return _this;
810
- });
811
- };
812
- /**
813
- * Refreshes the current `token` and `tokenExpires` with `refreshToken`.
814
- */
815
- UserSession.prototype.refreshWithRefreshToken = function (requestOptions) {
816
- var _this = this;
817
- if (this.refreshToken &&
818
- this.refreshTokenExpires &&
819
- this.refreshTokenExpires.getTime() < Date.now()) {
820
- return this.refreshRefreshToken(requestOptions);
821
- }
822
- var options = __assign({ params: {
823
- client_id: this.clientId,
824
- refresh_token: this.refreshToken,
825
- grant_type: "refresh_token",
826
- } }, requestOptions);
827
- return fetchToken(this.portal + "/oauth2/token", options).then(function (response) {
828
- _this._token = response.token;
829
- _this._tokenExpires = response.expires;
830
- return _this;
831
- });
832
- };
833
- /**
834
- * Exchanges an unexpired `refreshToken` for a new one, also updates `token` and
835
- * `tokenExpires`.
836
- */
837
- UserSession.prototype.refreshRefreshToken = function (requestOptions) {
838
- var _this = this;
839
- var options = __assign({ params: {
840
- client_id: this.clientId,
841
- refresh_token: this.refreshToken,
842
- redirect_uri: this.redirectUri,
843
- grant_type: "exchange_refresh_token",
844
- } }, requestOptions);
845
- return fetchToken(this.portal + "/oauth2/token", options).then(function (response) {
846
- _this._token = response.token;
847
- _this._tokenExpires = response.expires;
848
- _this._refreshToken = response.refreshToken;
849
- _this._refreshTokenExpires = new Date(Date.now() + (_this.refreshTokenTTL - 1) * 60 * 1000);
850
- return _this;
851
- });
852
- };
853
- /**
854
- * ensures that the authorizedCrossOriginDomains are obtained from the portal and cached
855
- * so we can check them later.
856
- *
857
- * @returns this
858
- */
859
- UserSession.prototype.fetchAuthorizedDomains = function () {
860
- var _this = this;
861
- // if this token is for a specific server or we don't have a portal
862
- // don't get the portal info because we cant get the authorizedCrossOriginDomains
863
- if (this.server || !this.portal) {
864
- return Promise.resolve(this);
865
- }
866
- return this.getPortal().then(function (portalInfo) {
867
- /**
868
- * Specific domains can be configured as secure.esri.com or https://secure.esri.com this
869
- * normalizes to https://secure.esri.com so we can use startsWith later.
870
- */
871
- if (portalInfo.authorizedCrossOriginDomains &&
872
- portalInfo.authorizedCrossOriginDomains.length) {
873
- _this.trustedDomains = portalInfo.authorizedCrossOriginDomains
874
- .filter(function (d) { return !d.startsWith("http://"); })
875
- .map(function (d) {
876
- if (d.startsWith("https://")) {
877
- return d;
878
- }
879
- else {
880
- return "https://" + d;
881
- }
882
- });
883
- }
884
- return _this;
885
- });
886
- };
887
- return UserSession;
888
- }());
889
- export { UserSession };
890
- //# sourceMappingURL=UserSession.js.map