@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,1253 +0,0 @@
1
- /* @preserve
2
- * @esri/arcgis-rest-auth - v3.4.2 - Apache-2.0
3
- * Copyright (c) 2017-2021 Esri, Inc.
4
- * Sat Oct 23 2021 08:28:16 GMT-0600 (Mountain Daylight Time)
5
- */
6
- (function (global, factory) {
7
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@esri/arcgis-rest-request')) :
8
- typeof define === 'function' && define.amd ? define(['exports', '@esri/arcgis-rest-request'], factory) :
9
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.arcgisRest = global.arcgisRest || {}, global.arcgisRest));
10
- }(this, (function (exports, arcgisRestRequest) { 'use strict';
11
-
12
- /*! *****************************************************************************
13
- Copyright (c) Microsoft Corporation.
14
-
15
- Permission to use, copy, modify, and/or distribute this software for any
16
- purpose with or without fee is hereby granted.
17
-
18
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
19
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
20
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
22
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
23
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
24
- PERFORMANCE OF THIS SOFTWARE.
25
- ***************************************************************************** */
26
-
27
- var __assign = function() {
28
- __assign = Object.assign || function __assign(t) {
29
- for (var s, i = 1, n = arguments.length; i < n; i++) {
30
- s = arguments[i];
31
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
32
- }
33
- return t;
34
- };
35
- return __assign.apply(this, arguments);
36
- };
37
-
38
- /* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
39
- * Apache-2.0 */
40
- function fetchToken(url, requestOptions) {
41
- var options = requestOptions;
42
- // we generate a response, so we can't return the raw response
43
- options.rawResponse = false;
44
- return arcgisRestRequest.request(url, options).then(function (response) {
45
- var r = {
46
- token: response.access_token,
47
- username: response.username,
48
- expires: new Date(
49
- // convert seconds in response to milliseconds and add the value to the current time to calculate a static expiration timestamp
50
- Date.now() + (response.expires_in * 1000 - 1000)),
51
- ssl: response.ssl === true
52
- };
53
- if (response.refresh_token) {
54
- r.refreshToken = response.refresh_token;
55
- }
56
- return r;
57
- });
58
- }
59
-
60
- /* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.
61
- * Apache-2.0 */
62
- /**
63
- * ```js
64
- * import { ApplicationSession } from '@esri/arcgis-rest-auth';
65
- * const session = new ApplicationSession({
66
- * clientId: "abc123",
67
- * clientSecret: "sshhhhhh"
68
- * })
69
- * // visit https://developers.arcgis.com to generate your own clientid and secret
70
- * ```
71
- * You can use [App Login](/arcgis-rest-js/guides/node/) to access premium content and services in ArcGIS Online.
72
- *
73
- */
74
- var ApplicationSession = /** @class */ (function () {
75
- function ApplicationSession(options) {
76
- this.clientId = options.clientId;
77
- this.clientSecret = options.clientSecret;
78
- this.token = options.token;
79
- this.expires = options.expires;
80
- this.portal = options.portal || "https://www.arcgis.com/sharing/rest";
81
- this.duration = options.duration || 7200;
82
- }
83
- // URL is not actually read or passed through.
84
- ApplicationSession.prototype.getToken = function (url, requestOptions) {
85
- if (this.token && this.expires && this.expires.getTime() > Date.now()) {
86
- return Promise.resolve(this.token);
87
- }
88
- if (this._pendingTokenRequest) {
89
- return this._pendingTokenRequest;
90
- }
91
- this._pendingTokenRequest = this.refreshToken(requestOptions);
92
- return this._pendingTokenRequest;
93
- };
94
- ApplicationSession.prototype.refreshToken = function (requestOptions) {
95
- var _this = this;
96
- var options = __assign({ params: {
97
- client_id: this.clientId,
98
- client_secret: this.clientSecret,
99
- grant_type: "client_credentials",
100
- expiration: this.duration
101
- } }, requestOptions);
102
- return fetchToken(this.portal + "/oauth2/token/", options).then(function (response) {
103
- _this._pendingTokenRequest = null;
104
- _this.token = response.token;
105
- _this.expires = response.expires;
106
- return response.token;
107
- });
108
- };
109
- ApplicationSession.prototype.refreshSession = function () {
110
- var _this = this;
111
- return this.refreshToken().then(function () { return _this; });
112
- };
113
- return ApplicationSession;
114
- }());
115
-
116
- /* Copyright (c) 2017-2019 Environmental Systems Research Institute, Inc.
117
- * Apache-2.0 */
118
- /**
119
- * ```js
120
- * import { ApiKey } from '@esri/arcgis-rest-auth';
121
- * const apiKey = new ApiKey("...");
122
- * ```
123
- * Used to authenticate with API Keys.
124
- */
125
- var ApiKey = /** @class */ (function () {
126
- function ApiKey(options) {
127
- this.key = options.key;
128
- }
129
- /**
130
- * Gets a token (the API Key).
131
- */
132
- ApiKey.prototype.getToken = function (url) {
133
- return Promise.resolve(this.key);
134
- };
135
- return ApiKey;
136
- }());
137
-
138
- /* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.
139
- * Apache-2.0 */
140
- function generateToken(url, requestOptions) {
141
- var options = requestOptions;
142
- /* istanbul ignore else */
143
- if (typeof window !== "undefined" &&
144
- window.location &&
145
- window.location.host) {
146
- options.params.referer = window.location.host;
147
- }
148
- else {
149
- options.params.referer = arcgisRestRequest.NODEJS_DEFAULT_REFERER_HEADER;
150
- }
151
- return arcgisRestRequest.request(url, options);
152
- }
153
-
154
- /**
155
- * Used to test if a URL is an ArcGIS Online URL
156
- */
157
- var arcgisOnlineUrlRegex = /^https?:\/\/(\S+)\.arcgis\.com.+/;
158
- function isOnline(url) {
159
- return arcgisOnlineUrlRegex.test(url);
160
- }
161
- function normalizeOnlinePortalUrl(portalUrl) {
162
- if (!arcgisOnlineUrlRegex.test(portalUrl)) {
163
- return portalUrl;
164
- }
165
- switch (getOnlineEnvironment(portalUrl)) {
166
- case "dev":
167
- return "https://devext.arcgis.com/sharing/rest";
168
- case "qa":
169
- return "https://qaext.arcgis.com/sharing/rest";
170
- default:
171
- return "https://www.arcgis.com/sharing/rest";
172
- }
173
- }
174
- function getOnlineEnvironment(url) {
175
- if (!arcgisOnlineUrlRegex.test(url)) {
176
- return null;
177
- }
178
- var match = url.match(arcgisOnlineUrlRegex);
179
- var subdomain = match[1].split(".").pop();
180
- if (subdomain.includes("dev")) {
181
- return "dev";
182
- }
183
- if (subdomain.includes("qa")) {
184
- return "qa";
185
- }
186
- return "production";
187
- }
188
- function isFederated(owningSystemUrl, portalUrl) {
189
- var normalizedPortalUrl = arcgisRestRequest.cleanUrl(normalizeOnlinePortalUrl(portalUrl)).replace(/https?:\/\//, "");
190
- var normalizedOwningSystemUrl = arcgisRestRequest.cleanUrl(owningSystemUrl).replace(/https?:\/\//, "");
191
- return new RegExp(normalizedOwningSystemUrl, "i").test(normalizedPortalUrl);
192
- }
193
- function canUseOnlineToken(portalUrl, requestUrl) {
194
- var portalIsOnline = isOnline(portalUrl);
195
- var requestIsOnline = isOnline(requestUrl);
196
- var portalEnv = getOnlineEnvironment(portalUrl);
197
- var requestEnv = getOnlineEnvironment(requestUrl);
198
- if (portalIsOnline && requestIsOnline && portalEnv === requestEnv) {
199
- return true;
200
- }
201
- return false;
202
- }
203
-
204
- /* Copyright (c) 2018-2020 Environmental Systems Research Institute, Inc.
205
- * Apache-2.0 */
206
- /**
207
- * Validates that the user has access to the application
208
- * and if they user should be presented a "View Only" mode
209
- *
210
- * This is only needed/valid for Esri applications that are "licensed"
211
- * and shipped in ArcGIS Online or ArcGIS Enterprise. Most custom applications
212
- * should not need or use this.
213
- *
214
- * ```js
215
- * import { validateAppAccess } from '@esri/arcgis-rest-auth';
216
- *
217
- * return validateAppAccess('your-token', 'theClientId')
218
- * .then((result) => {
219
- * if (!result.value) {
220
- * // redirect or show some other ui
221
- * } else {
222
- * if (result.viewOnlyUserTypeApp) {
223
- * // use this to inform your app to show a "View Only" mode
224
- * }
225
- * }
226
- * })
227
- * .catch((err) => {
228
- * // two possible errors
229
- * // invalid clientId: {"error":{"code":400,"messageCode":"GWM_0007","message":"Invalid request","details":[]}}
230
- * // invalid token: {"error":{"code":498,"message":"Invalid token.","details":[]}}
231
- * })
232
- * ```
233
- *
234
- * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within
235
- * an ArcGIS Enterprise installation. Custom applications can not use this.
236
- *
237
- * @param token platform token
238
- * @param clientId application client id
239
- * @param portal Optional
240
- */
241
- function validateAppAccess(token, clientId, portal) {
242
- if (portal === void 0) { portal = "https://www.arcgis.com/sharing/rest"; }
243
- var url = portal + "/oauth2/validateAppAccess";
244
- var ro = {
245
- method: "POST",
246
- params: {
247
- f: "json",
248
- client_id: clientId,
249
- token: token,
250
- },
251
- };
252
- return arcgisRestRequest.request(url, ro);
253
- }
254
-
255
- /* Copyright (c) 2017-2019 Environmental Systems Research Institute, Inc.
256
- * Apache-2.0 */
257
- function defer() {
258
- var deferred = {
259
- promise: null,
260
- resolve: null,
261
- reject: null,
262
- };
263
- deferred.promise = new Promise(function (resolve, reject) {
264
- deferred.resolve = resolve;
265
- deferred.reject = reject;
266
- });
267
- return deferred;
268
- }
269
- /**
270
- * ```js
271
- * import { UserSession } from '@esri/arcgis-rest-auth';
272
- * UserSession.beginOAuth2({
273
- * // register an app of your own to create a unique clientId
274
- * clientId: "abc123",
275
- * redirectUri: 'https://yourapp.com/authenticate.html'
276
- * })
277
- * .then(session)
278
- * // or
279
- * new UserSession({
280
- * username: "jsmith",
281
- * password: "123456"
282
- * })
283
- * // or
284
- * UserSession.deserialize(cache)
285
- * ```
286
- * 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.
287
- */
288
- var UserSession = /** @class */ (function () {
289
- function UserSession(options) {
290
- this.clientId = options.clientId;
291
- this._refreshToken = options.refreshToken;
292
- this._refreshTokenExpires = options.refreshTokenExpires;
293
- this.username = options.username;
294
- this.password = options.password;
295
- this._token = options.token;
296
- this._tokenExpires = options.tokenExpires;
297
- this.portal = options.portal
298
- ? arcgisRestRequest.cleanUrl(options.portal)
299
- : "https://www.arcgis.com/sharing/rest";
300
- this.ssl = options.ssl;
301
- this.provider = options.provider || "arcgis";
302
- this.tokenDuration = options.tokenDuration || 20160;
303
- this.redirectUri = options.redirectUri;
304
- this.refreshTokenTTL = options.refreshTokenTTL || 20160;
305
- this.server = options.server;
306
- this.federatedServers = {};
307
- this.trustedDomains = [];
308
- // if a non-federated server was passed explicitly, it should be trusted.
309
- if (options.server) {
310
- // if the url includes more than '/arcgis/', trim the rest
311
- var root = this.getServerRootUrl(options.server);
312
- this.federatedServers[root] = {
313
- token: options.token,
314
- expires: options.tokenExpires,
315
- };
316
- }
317
- this._pendingTokenRequests = {};
318
- }
319
- Object.defineProperty(UserSession.prototype, "token", {
320
- /**
321
- * The current ArcGIS Online or ArcGIS Enterprise `token`.
322
- */
323
- get: function () {
324
- return this._token;
325
- },
326
- enumerable: false,
327
- configurable: true
328
- });
329
- Object.defineProperty(UserSession.prototype, "tokenExpires", {
330
- /**
331
- * The expiration time of the current `token`.
332
- */
333
- get: function () {
334
- return this._tokenExpires;
335
- },
336
- enumerable: false,
337
- configurable: true
338
- });
339
- Object.defineProperty(UserSession.prototype, "refreshToken", {
340
- /**
341
- * The current token to ArcGIS Online or ArcGIS Enterprise.
342
- */
343
- get: function () {
344
- return this._refreshToken;
345
- },
346
- enumerable: false,
347
- configurable: true
348
- });
349
- Object.defineProperty(UserSession.prototype, "refreshTokenExpires", {
350
- /**
351
- * The expiration time of the current `refreshToken`.
352
- */
353
- get: function () {
354
- return this._refreshTokenExpires;
355
- },
356
- enumerable: false,
357
- configurable: true
358
- });
359
- Object.defineProperty(UserSession.prototype, "trustedServers", {
360
- /**
361
- * Deprecated, use `federatedServers` instead.
362
- *
363
- * @deprecated
364
- */
365
- get: function () {
366
- console.log("DEPRECATED: use federatedServers instead");
367
- return this.federatedServers;
368
- },
369
- enumerable: false,
370
- configurable: true
371
- });
372
- /**
373
- * Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is `true` the
374
- * authentication window will open in a new tab/window and the function will return
375
- * Promise&lt;UserSession&gt;. Otherwise, the user will be redirected to the
376
- * authorization page in their current tab/window and the function will return `undefined`.
377
- *
378
- * @browserOnly
379
- */
380
- /* istanbul ignore next */
381
- UserSession.beginOAuth2 = function (options, win) {
382
- if (win === void 0) { win = window; }
383
- if (options.duration) {
384
- console.log("DEPRECATED: 'duration' is deprecated - use 'expiration' instead");
385
- }
386
- var _a = __assign({
387
- portal: "https://www.arcgis.com/sharing/rest",
388
- provider: "arcgis",
389
- expiration: 20160,
390
- popup: true,
391
- popupWindowFeatures: "height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",
392
- state: options.clientId,
393
- locale: "",
394
- }, 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;
395
- var url;
396
- if (provider === "arcgis") {
397
- url = portal + "/oauth2/authorize?client_id=" + clientId + "&response_type=token&expiration=" + (options.duration || expiration) + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&state=" + state + "&locale=" + locale;
398
- }
399
- else {
400
- 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;
401
- }
402
- // append additional params
403
- if (params) {
404
- url = url + "&" + arcgisRestRequest.encodeQueryString(params);
405
- }
406
- if (!popup) {
407
- win.location.href = url;
408
- return undefined;
409
- }
410
- var session = defer();
411
- win["__ESRI_REST_AUTH_HANDLER_" + clientId] = function (errorString, oauthInfoString) {
412
- if (errorString) {
413
- var error = JSON.parse(errorString);
414
- session.reject(new arcgisRestRequest.ArcGISAuthError(error.errorMessage, error.error));
415
- return;
416
- }
417
- if (oauthInfoString) {
418
- var oauthInfo = JSON.parse(oauthInfoString);
419
- session.resolve(new UserSession({
420
- clientId: clientId,
421
- portal: portal,
422
- ssl: oauthInfo.ssl,
423
- token: oauthInfo.token,
424
- tokenExpires: new Date(oauthInfo.expires),
425
- username: oauthInfo.username,
426
- }));
427
- }
428
- };
429
- win.open(url, "oauth-window", popupWindowFeatures);
430
- return session.promise;
431
- };
432
- /**
433
- * Completes a browser-based OAuth 2.0 sign in. If `options.popup` is `true` the user
434
- * will be returned to the previous window. Otherwise a new `UserSession`
435
- * will be returned. You must pass the same values for `options.popup` and
436
- * `options.portal` as you used in `beginOAuth2()`.
437
- *
438
- * @browserOnly
439
- */
440
- /* istanbul ignore next */
441
- UserSession.completeOAuth2 = function (options, win) {
442
- if (win === void 0) { win = window; }
443
- var _a = __assign({ portal: "https://www.arcgis.com/sharing/rest", popup: true }, options), portal = _a.portal, clientId = _a.clientId, popup = _a.popup;
444
- function completeSignIn(error, oauthInfo) {
445
- try {
446
- var handlerFn = void 0;
447
- var handlerFnName = "__ESRI_REST_AUTH_HANDLER_" + clientId;
448
- if (popup) {
449
- // Guard b/c IE does not support window.opener
450
- if (win.opener) {
451
- if (win.opener.parent && win.opener.parent[handlerFnName]) {
452
- handlerFn = win.opener.parent[handlerFnName];
453
- }
454
- else if (win.opener && win.opener[handlerFnName]) {
455
- // support pop-out oauth from within an iframe
456
- handlerFn = win.opener[handlerFnName];
457
- }
458
- }
459
- else {
460
- // IE
461
- if (win !== win.parent && win.parent && win.parent[handlerFnName]) {
462
- handlerFn = win.parent[handlerFnName];
463
- }
464
- }
465
- // if we have a handler fn, call it and close the window
466
- if (handlerFn) {
467
- handlerFn(error ? JSON.stringify(error) : undefined, JSON.stringify(oauthInfo));
468
- win.close();
469
- return undefined;
470
- }
471
- }
472
- }
473
- catch (e) {
474
- throw new arcgisRestRequest.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()\".");
475
- }
476
- if (error) {
477
- throw new arcgisRestRequest.ArcGISAuthError(error.errorMessage, error.error);
478
- }
479
- return new UserSession({
480
- clientId: clientId,
481
- portal: portal,
482
- ssl: oauthInfo.ssl,
483
- token: oauthInfo.token,
484
- tokenExpires: oauthInfo.expires,
485
- username: oauthInfo.username,
486
- });
487
- }
488
- var params = arcgisRestRequest.decodeQueryString(win.location.hash);
489
- if (!params.access_token) {
490
- var error = void 0;
491
- var errorMessage = "Unknown error";
492
- if (params.error) {
493
- error = params.error;
494
- errorMessage = params.error_description;
495
- }
496
- return completeSignIn({ error: error, errorMessage: errorMessage });
497
- }
498
- var token = params.access_token;
499
- var expires = new Date(Date.now() + parseInt(params.expires_in, 10) * 1000 - 60 * 1000);
500
- var username = params.username;
501
- var ssl = params.ssl === "true";
502
- return completeSignIn(undefined, {
503
- token: token,
504
- expires: expires,
505
- ssl: ssl,
506
- username: username,
507
- });
508
- };
509
- /**
510
- * Request session information from the parent application
511
- *
512
- * When an application is embedded into another application via an IFrame, the embedded app can
513
- * use `window.postMessage` to request credentials from the host application. This function wraps
514
- * that behavior.
515
- *
516
- * The ArcGIS API for Javascript has this built into the Identity Manager as of the 4.19 release.
517
- *
518
- * Note: The parent application will not respond if the embedded app's origin is not:
519
- * - the same origin as the parent or *.arcgis.com (JSAPI)
520
- * - in the list of valid child origins (REST-JS)
521
- *
522
- *
523
- * @param parentOrigin origin of the parent frame. Passed into the embedded application as `parentOrigin` query param
524
- * @browserOnly
525
- */
526
- UserSession.fromParent = function (parentOrigin, win) {
527
- /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */
528
- if (!win && window) {
529
- win = window;
530
- }
531
- // Declare handler outside of promise scope so we can detach it
532
- var handler;
533
- // return a promise that will resolve when the handler receives
534
- // session information from the correct origin
535
- return new Promise(function (resolve, reject) {
536
- // create an event handler that just wraps the parentMessageHandler
537
- handler = function (event) {
538
- // ensure we only listen to events from the parent
539
- if (event.source === win.parent && event.data) {
540
- try {
541
- return resolve(UserSession.parentMessageHandler(event));
542
- }
543
- catch (err) {
544
- return reject(err);
545
- }
546
- }
547
- };
548
- // add listener
549
- win.addEventListener("message", handler, false);
550
- win.parent.postMessage({ type: "arcgis:auth:requestCredential" }, parentOrigin);
551
- }).then(function (session) {
552
- win.removeEventListener("message", handler, false);
553
- return session;
554
- });
555
- };
556
- /**
557
- * Begins a new server-based OAuth 2.0 sign in. This will redirect the user to
558
- * the ArcGIS Online or ArcGIS Enterprise authorization page.
559
- *
560
- * @nodeOnly
561
- */
562
- UserSession.authorize = function (options, response) {
563
- if (options.duration) {
564
- console.log("DEPRECATED: 'duration' is deprecated - use 'expiration' instead");
565
- }
566
- var _a = __assign({ portal: "https://arcgis.com/sharing/rest", expiration: 20160 }, options), portal = _a.portal, clientId = _a.clientId, expiration = _a.expiration, redirectUri = _a.redirectUri;
567
- response.writeHead(301, {
568
- Location: portal + "/oauth2/authorize?client_id=" + clientId + "&expiration=" + (options.duration || expiration) + "&response_type=code&redirect_uri=" + encodeURIComponent(redirectUri),
569
- });
570
- response.end();
571
- };
572
- /**
573
- * Completes the server-based OAuth 2.0 sign in process by exchanging the `authorizationCode`
574
- * for a `access_token`.
575
- *
576
- * @nodeOnly
577
- */
578
- UserSession.exchangeAuthorizationCode = function (options, authorizationCode) {
579
- var _a = __assign({
580
- portal: "https://www.arcgis.com/sharing/rest",
581
- refreshTokenTTL: 20160,
582
- }, options), portal = _a.portal, clientId = _a.clientId, redirectUri = _a.redirectUri, refreshTokenTTL = _a.refreshTokenTTL;
583
- return fetchToken(portal + "/oauth2/token", {
584
- params: {
585
- grant_type: "authorization_code",
586
- client_id: clientId,
587
- redirect_uri: redirectUri,
588
- code: authorizationCode,
589
- },
590
- }).then(function (response) {
591
- return new UserSession({
592
- clientId: clientId,
593
- portal: portal,
594
- ssl: response.ssl,
595
- redirectUri: redirectUri,
596
- refreshToken: response.refreshToken,
597
- refreshTokenTTL: refreshTokenTTL,
598
- refreshTokenExpires: new Date(Date.now() + (refreshTokenTTL - 1) * 60 * 1000),
599
- token: response.token,
600
- tokenExpires: response.expires,
601
- username: response.username,
602
- });
603
- });
604
- };
605
- UserSession.deserialize = function (str) {
606
- var options = JSON.parse(str);
607
- return new UserSession({
608
- clientId: options.clientId,
609
- refreshToken: options.refreshToken,
610
- refreshTokenExpires: new Date(options.refreshTokenExpires),
611
- username: options.username,
612
- password: options.password,
613
- token: options.token,
614
- tokenExpires: new Date(options.tokenExpires),
615
- portal: options.portal,
616
- ssl: options.ssl,
617
- tokenDuration: options.tokenDuration,
618
- redirectUri: options.redirectUri,
619
- refreshTokenTTL: options.refreshTokenTTL,
620
- });
621
- };
622
- /**
623
- * Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).
624
- *
625
- * ```js
626
- * UserSession.fromCredential({
627
- * userId: "jsmith",
628
- * token: "secret"
629
- * });
630
- * ```
631
- *
632
- * @returns UserSession
633
- */
634
- UserSession.fromCredential = function (credential) {
635
- // At ArcGIS Online 9.1, credentials no longer include the ssl and expires properties
636
- // Here, we provide default values for them to cover this condition
637
- var ssl = typeof credential.ssl !== "undefined" ? credential.ssl : true;
638
- var expires = credential.expires || Date.now() + 7200000 /* 2 hours */;
639
- return new UserSession({
640
- portal: credential.server.includes("sharing/rest")
641
- ? credential.server
642
- : credential.server + "/sharing/rest",
643
- ssl: ssl,
644
- token: credential.token,
645
- username: credential.userId,
646
- tokenExpires: new Date(expires),
647
- });
648
- };
649
- /**
650
- * Handle the response from the parent
651
- * @param event DOM Event
652
- */
653
- UserSession.parentMessageHandler = function (event) {
654
- if (event.data.type === "arcgis:auth:credential") {
655
- return UserSession.fromCredential(event.data.credential);
656
- }
657
- if (event.data.type === "arcgis:auth:error") {
658
- var err = new Error(event.data.error.message);
659
- err.name = event.data.error.name;
660
- throw err;
661
- }
662
- else {
663
- throw new Error("Unknown message type.");
664
- }
665
- };
666
- /**
667
- * Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).
668
- *
669
- * ```js
670
- * esriId.registerToken(session.toCredential());
671
- * ```
672
- *
673
- * @returns ICredential
674
- */
675
- UserSession.prototype.toCredential = function () {
676
- return {
677
- expires: this.tokenExpires.getTime(),
678
- server: this.portal,
679
- ssl: this.ssl,
680
- token: this.token,
681
- userId: this.username,
682
- };
683
- };
684
- /**
685
- * 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.
686
- *
687
- * ```js
688
- * session.getUser()
689
- * .then(response => {
690
- * console.log(response.role); // "org_admin"
691
- * })
692
- * ```
693
- *
694
- * @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.
695
- * @returns A Promise that will resolve with the data from the response.
696
- */
697
- UserSession.prototype.getUser = function (requestOptions) {
698
- var _this = this;
699
- if (this._pendingUserRequest) {
700
- return this._pendingUserRequest;
701
- }
702
- else if (this._user) {
703
- return Promise.resolve(this._user);
704
- }
705
- else {
706
- var url = this.portal + "/community/self";
707
- var options = __assign(__assign({ httpMethod: "GET", authentication: this }, requestOptions), { rawResponse: false });
708
- this._pendingUserRequest = arcgisRestRequest.request(url, options).then(function (response) {
709
- _this._user = response;
710
- _this._pendingUserRequest = null;
711
- return response;
712
- });
713
- return this._pendingUserRequest;
714
- }
715
- };
716
- /**
717
- * 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.
718
- *
719
- * ```js
720
- * session.getPortal()
721
- * .then(response => {
722
- * console.log(portal.name); // "City of ..."
723
- * })
724
- * ```
725
- *
726
- * @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.
727
- * @returns A Promise that will resolve with the data from the response.
728
- */
729
- UserSession.prototype.getPortal = function (requestOptions) {
730
- var _this = this;
731
- if (this._pendingPortalRequest) {
732
- return this._pendingPortalRequest;
733
- }
734
- else if (this._portalInfo) {
735
- return Promise.resolve(this._portalInfo);
736
- }
737
- else {
738
- var url = this.portal + "/portals/self";
739
- var options = __assign(__assign({ httpMethod: "GET", authentication: this }, requestOptions), { rawResponse: false });
740
- this._pendingPortalRequest = arcgisRestRequest.request(url, options).then(function (response) {
741
- _this._portalInfo = response;
742
- _this._pendingPortalRequest = null;
743
- return response;
744
- });
745
- return this._pendingPortalRequest;
746
- }
747
- };
748
- /**
749
- * 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.
750
- *
751
- * * ```js
752
- * session.getUsername()
753
- * .then(response => {
754
- * console.log(response); // "casey_jones"
755
- * })
756
- * ```
757
- */
758
- UserSession.prototype.getUsername = function () {
759
- if (this.username) {
760
- return Promise.resolve(this.username);
761
- }
762
- else if (this._user) {
763
- return Promise.resolve(this._user.username);
764
- }
765
- else {
766
- return this.getUser().then(function (user) {
767
- return user.username;
768
- });
769
- }
770
- };
771
- /**
772
- * Gets an appropriate token for the given URL. If `portal` is ArcGIS Online and
773
- * the request is to an ArcGIS Online domain `token` will be used. If the request
774
- * is to the current `portal` the current `token` will also be used. However if
775
- * the request is to an unknown server we will validate the server with a request
776
- * to our current `portal`.
777
- */
778
- UserSession.prototype.getToken = function (url, requestOptions) {
779
- if (canUseOnlineToken(this.portal, url)) {
780
- return this.getFreshToken(requestOptions);
781
- }
782
- else if (new RegExp(this.portal, "i").test(url)) {
783
- return this.getFreshToken(requestOptions);
784
- }
785
- else {
786
- return this.getTokenForServer(url, requestOptions);
787
- }
788
- };
789
- /**
790
- * Get application access information for the current user
791
- * see `validateAppAccess` function for details
792
- *
793
- * @param clientId application client id
794
- */
795
- UserSession.prototype.validateAppAccess = function (clientId) {
796
- return this.getToken(this.portal).then(function (token) {
797
- return validateAppAccess(token, clientId);
798
- });
799
- };
800
- UserSession.prototype.toJSON = function () {
801
- return {
802
- clientId: this.clientId,
803
- refreshToken: this.refreshToken,
804
- refreshTokenExpires: this.refreshTokenExpires,
805
- username: this.username,
806
- password: this.password,
807
- token: this.token,
808
- tokenExpires: this.tokenExpires,
809
- portal: this.portal,
810
- ssl: this.ssl,
811
- tokenDuration: this.tokenDuration,
812
- redirectUri: this.redirectUri,
813
- refreshTokenTTL: this.refreshTokenTTL,
814
- };
815
- };
816
- UserSession.prototype.serialize = function () {
817
- return JSON.stringify(this);
818
- };
819
- /**
820
- * For a "Host" app that embeds other platform apps via iframes, after authenticating the user
821
- * and creating a UserSession, the app can then enable "post message" style authentication by calling
822
- * this method.
823
- *
824
- * Internally this adds an event listener on window for the `message` event
825
- *
826
- * @param validChildOrigins Array of origins that are allowed to request authentication from the host app
827
- */
828
- UserSession.prototype.enablePostMessageAuth = function (validChildOrigins, win) {
829
- /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */
830
- if (!win && window) {
831
- win = window;
832
- }
833
- this._hostHandler = this.createPostMessageHandler(validChildOrigins);
834
- win.addEventListener("message", this._hostHandler, false);
835
- };
836
- /**
837
- * For a "Host" app that has embedded other platform apps via iframes, when the host needs
838
- * to transition routes, it should call `UserSession.disablePostMessageAuth()` to remove
839
- * the event listener and prevent memory leaks
840
- */
841
- UserSession.prototype.disablePostMessageAuth = function (win) {
842
- /* istanbul ignore next: must pass in a mockwindow for tests so we can't cover the other branch */
843
- if (!win && window) {
844
- win = window;
845
- }
846
- win.removeEventListener("message", this._hostHandler, false);
847
- };
848
- /**
849
- * Manually refreshes the current `token` and `tokenExpires`.
850
- */
851
- UserSession.prototype.refreshSession = function (requestOptions) {
852
- // make sure subsequent calls to getUser() don't returned cached metadata
853
- this._user = null;
854
- if (this.username && this.password) {
855
- return this.refreshWithUsernameAndPassword(requestOptions);
856
- }
857
- if (this.clientId && this.refreshToken) {
858
- return this.refreshWithRefreshToken();
859
- }
860
- return Promise.reject(new arcgisRestRequest.ArcGISAuthError("Unable to refresh token."));
861
- };
862
- /**
863
- * Determines the root of the ArcGIS Server or Portal for a given URL.
864
- *
865
- * @param url the URl to determine the root url for.
866
- */
867
- UserSession.prototype.getServerRootUrl = function (url) {
868
- var root = arcgisRestRequest.cleanUrl(url).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/)[0];
869
- var _a = root.match(/(https?:\/\/)(.+)/), match = _a[0], protocol = _a[1], domainAndPath = _a[2];
870
- var _b = domainAndPath.split("/"), domain = _b[0], path = _b.slice(1);
871
- // only the domain is lowercased because in some cases an org id might be
872
- // in the path which cannot be lowercased.
873
- return "" + protocol + domain.toLowerCase() + "/" + path.join("/");
874
- };
875
- /**
876
- * Returns the proper [`credentials`] option for `fetch` for a given domain.
877
- * See [trusted server](https://enterprise.arcgis.com/en/portal/latest/administer/windows/configure-security.htm#ESRI_SECTION1_70CC159B3540440AB325BE5D89DBE94A).
878
- * Used internally by underlying request methods to add support for specific security considerations.
879
- *
880
- * @param url The url of the request
881
- * @returns "include" or "same-origin"
882
- */
883
- UserSession.prototype.getDomainCredentials = function (url) {
884
- if (!this.trustedDomains || !this.trustedDomains.length) {
885
- return "same-origin";
886
- }
887
- return this.trustedDomains.some(function (domainWithProtocol) {
888
- return url.startsWith(domainWithProtocol);
889
- })
890
- ? "include"
891
- : "same-origin";
892
- };
893
- /**
894
- * Return a function that closes over the validOrigins array and
895
- * can be used as an event handler for the `message` event
896
- *
897
- * @param validOrigins Array of valid origins
898
- */
899
- UserSession.prototype.createPostMessageHandler = function (validOrigins) {
900
- var _this = this;
901
- // return a function that closes over the validOrigins and
902
- // has access to the credential
903
- return function (event) {
904
- // Verify that the origin is valid
905
- // Note: do not use regex's here. validOrigins is an array so we're checking that the event's origin
906
- // is in the array via exact match. More info about avoiding postMessage xss issues here
907
- // https://jlajara.gitlab.io/web/2020/07/17/Dom_XSS_PostMessage_2.html#tipsbypasses-in-postmessage-vulnerabilities
908
- var isValidOrigin = validOrigins.indexOf(event.origin) > -1;
909
- // JSAPI handles this slightly differently - instead of checking a list, it will respond if
910
- // event.origin === window.location.origin || event.origin.endsWith('.arcgis.com')
911
- // For Hub, and to enable cross domain debugging with port's in urls, we are opting to
912
- // use a list of valid origins
913
- // Ensure the message type is something we want to handle
914
- var isValidType = event.data.type === "arcgis:auth:requestCredential";
915
- if (isValidOrigin && isValidType) {
916
- var credential = _this.toCredential();
917
- // the following line allows us to conform to our spec without changing other depended-on functionality
918
- // https://github.com/Esri/arcgis-rest-js/blob/master/packages/arcgis-rest-auth/post-message-auth-spec.md#arcgisauthcredential
919
- credential.server = credential.server.replace("/sharing/rest", "");
920
- event.source.postMessage({
921
- type: "arcgis:auth:credential",
922
- credential: credential,
923
- }, event.origin);
924
- }
925
- };
926
- };
927
- /**
928
- * Validates that a given URL is properly federated with our current `portal`.
929
- * Attempts to use the internal `federatedServers` cache first.
930
- */
931
- UserSession.prototype.getTokenForServer = function (url, requestOptions) {
932
- var _this = this;
933
- // requests to /rest/services/ and /rest/admin/services/ are both valid
934
- // Federated servers may have inconsistent casing, so lowerCase it
935
- var root = this.getServerRootUrl(url);
936
- var existingToken = this.federatedServers[root];
937
- if (existingToken &&
938
- existingToken.expires &&
939
- existingToken.expires.getTime() > Date.now()) {
940
- return Promise.resolve(existingToken.token);
941
- }
942
- if (this._pendingTokenRequests[root]) {
943
- return this._pendingTokenRequests[root];
944
- }
945
- this._pendingTokenRequests[root] = this.fetchAuthorizedDomains().then(function () {
946
- return arcgisRestRequest.request(root + "/rest/info", {
947
- credentials: _this.getDomainCredentials(url),
948
- })
949
- .then(function (response) {
950
- if (response.owningSystemUrl) {
951
- /**
952
- * if this server is not owned by this portal
953
- * bail out with an error since we know we wont
954
- * be able to generate a token
955
- */
956
- if (!isFederated(response.owningSystemUrl, _this.portal)) {
957
- throw new arcgisRestRequest.ArcGISAuthError(url + " is not federated with " + _this.portal + ".", "NOT_FEDERATED");
958
- }
959
- else {
960
- /**
961
- * if the server is federated, use the relevant token endpoint.
962
- */
963
- return arcgisRestRequest.request(response.owningSystemUrl + "/sharing/rest/info", requestOptions);
964
- }
965
- }
966
- else if (response.authInfo &&
967
- _this.federatedServers[root] !== undefined) {
968
- /**
969
- * if its a stand-alone instance of ArcGIS Server that doesn't advertise
970
- * federation, but the root server url is recognized, use its built in token endpoint.
971
- */
972
- return Promise.resolve({
973
- authInfo: response.authInfo,
974
- });
975
- }
976
- else {
977
- throw new arcgisRestRequest.ArcGISAuthError(url + " is not federated with any portal and is not explicitly trusted.", "NOT_FEDERATED");
978
- }
979
- })
980
- .then(function (response) {
981
- return response.authInfo.tokenServicesUrl;
982
- })
983
- .then(function (tokenServicesUrl) {
984
- // an expired token cant be used to generate a new token
985
- if (_this.token && _this.tokenExpires.getTime() > Date.now()) {
986
- return generateToken(tokenServicesUrl, {
987
- params: {
988
- token: _this.token,
989
- serverUrl: url,
990
- expiration: _this.tokenDuration,
991
- client: "referer",
992
- },
993
- });
994
- // generate an entirely fresh token if necessary
995
- }
996
- else {
997
- return generateToken(tokenServicesUrl, {
998
- params: {
999
- username: _this.username,
1000
- password: _this.password,
1001
- expiration: _this.tokenDuration,
1002
- client: "referer",
1003
- },
1004
- }).then(function (response) {
1005
- _this._token = response.token;
1006
- _this._tokenExpires = new Date(response.expires);
1007
- return response;
1008
- });
1009
- }
1010
- })
1011
- .then(function (response) {
1012
- _this.federatedServers[root] = {
1013
- expires: new Date(response.expires),
1014
- token: response.token,
1015
- };
1016
- delete _this._pendingTokenRequests[root];
1017
- return response.token;
1018
- });
1019
- });
1020
- return this._pendingTokenRequests[root];
1021
- };
1022
- /**
1023
- * Returns an unexpired token for the current `portal`.
1024
- */
1025
- UserSession.prototype.getFreshToken = function (requestOptions) {
1026
- var _this = this;
1027
- if (this.token && !this.tokenExpires) {
1028
- return Promise.resolve(this.token);
1029
- }
1030
- if (this.token &&
1031
- this.tokenExpires &&
1032
- this.tokenExpires.getTime() > Date.now()) {
1033
- return Promise.resolve(this.token);
1034
- }
1035
- if (!this._pendingTokenRequests[this.portal]) {
1036
- this._pendingTokenRequests[this.portal] = this.refreshSession(requestOptions).then(function (session) {
1037
- _this._pendingTokenRequests[_this.portal] = null;
1038
- return session.token;
1039
- });
1040
- }
1041
- return this._pendingTokenRequests[this.portal];
1042
- };
1043
- /**
1044
- * Refreshes the current `token` and `tokenExpires` with `username` and
1045
- * `password`.
1046
- */
1047
- UserSession.prototype.refreshWithUsernameAndPassword = function (requestOptions) {
1048
- var _this = this;
1049
- var options = __assign({ params: {
1050
- username: this.username,
1051
- password: this.password,
1052
- expiration: this.tokenDuration,
1053
- } }, requestOptions);
1054
- return generateToken(this.portal + "/generateToken", options).then(function (response) {
1055
- _this._token = response.token;
1056
- _this._tokenExpires = new Date(response.expires);
1057
- return _this;
1058
- });
1059
- };
1060
- /**
1061
- * Refreshes the current `token` and `tokenExpires` with `refreshToken`.
1062
- */
1063
- UserSession.prototype.refreshWithRefreshToken = function (requestOptions) {
1064
- var _this = this;
1065
- if (this.refreshToken &&
1066
- this.refreshTokenExpires &&
1067
- this.refreshTokenExpires.getTime() < Date.now()) {
1068
- return this.refreshRefreshToken(requestOptions);
1069
- }
1070
- var options = __assign({ params: {
1071
- client_id: this.clientId,
1072
- refresh_token: this.refreshToken,
1073
- grant_type: "refresh_token",
1074
- } }, requestOptions);
1075
- return fetchToken(this.portal + "/oauth2/token", options).then(function (response) {
1076
- _this._token = response.token;
1077
- _this._tokenExpires = response.expires;
1078
- return _this;
1079
- });
1080
- };
1081
- /**
1082
- * Exchanges an unexpired `refreshToken` for a new one, also updates `token` and
1083
- * `tokenExpires`.
1084
- */
1085
- UserSession.prototype.refreshRefreshToken = function (requestOptions) {
1086
- var _this = this;
1087
- var options = __assign({ params: {
1088
- client_id: this.clientId,
1089
- refresh_token: this.refreshToken,
1090
- redirect_uri: this.redirectUri,
1091
- grant_type: "exchange_refresh_token",
1092
- } }, requestOptions);
1093
- return fetchToken(this.portal + "/oauth2/token", options).then(function (response) {
1094
- _this._token = response.token;
1095
- _this._tokenExpires = response.expires;
1096
- _this._refreshToken = response.refreshToken;
1097
- _this._refreshTokenExpires = new Date(Date.now() + (_this.refreshTokenTTL - 1) * 60 * 1000);
1098
- return _this;
1099
- });
1100
- };
1101
- /**
1102
- * ensures that the authorizedCrossOriginDomains are obtained from the portal and cached
1103
- * so we can check them later.
1104
- *
1105
- * @returns this
1106
- */
1107
- UserSession.prototype.fetchAuthorizedDomains = function () {
1108
- var _this = this;
1109
- // if this token is for a specific server or we don't have a portal
1110
- // don't get the portal info because we cant get the authorizedCrossOriginDomains
1111
- if (this.server || !this.portal) {
1112
- return Promise.resolve(this);
1113
- }
1114
- return this.getPortal().then(function (portalInfo) {
1115
- /**
1116
- * Specific domains can be configured as secure.esri.com or https://secure.esri.com this
1117
- * normalizes to https://secure.esri.com so we can use startsWith later.
1118
- */
1119
- if (portalInfo.authorizedCrossOriginDomains &&
1120
- portalInfo.authorizedCrossOriginDomains.length) {
1121
- _this.trustedDomains = portalInfo.authorizedCrossOriginDomains
1122
- .filter(function (d) { return !d.startsWith("http://"); })
1123
- .map(function (d) {
1124
- if (d.startsWith("https://")) {
1125
- return d;
1126
- }
1127
- else {
1128
- return "https://" + d;
1129
- }
1130
- });
1131
- }
1132
- return _this;
1133
- });
1134
- };
1135
- return UserSession;
1136
- }());
1137
-
1138
- /* Copyright (c) 2018-2020 Environmental Systems Research Institute, Inc.
1139
- * Apache-2.0 */
1140
- /**
1141
- * Request app-specific token, passing in the token for the current app.
1142
- *
1143
- * This call returns a token after performing the same checks made by validateAppAccess.
1144
- * It returns an app-specific token of the signed-in user only if the user has access
1145
- * to the app and the encrypted platform cookie is valid.
1146
- *
1147
- * A scenario where an app would use this is if it is iframed into another platform app
1148
- * and receives credentials via postMessage. Those credentials contain a token that is
1149
- * specific to the host app, so the embedded app would use `exchangeToken` to get one
1150
- * that is specific to itself.
1151
- *
1152
- * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within
1153
- * an ArcGIS Enterprise installation. Custom applications can not use this.
1154
- *
1155
- * @param token
1156
- * @param clientId application
1157
- * @param portal
1158
- */
1159
- function exchangeToken(token, clientId, portal) {
1160
- if (portal === void 0) { portal = "https://www.arcgis.com/sharing/rest"; }
1161
- var url = portal + "/oauth2/exchangeToken";
1162
- var ro = {
1163
- method: "POST",
1164
- params: {
1165
- f: "json",
1166
- client_id: clientId,
1167
- token: token,
1168
- },
1169
- };
1170
- // make the request and return the token
1171
- return arcgisRestRequest.request(url, ro).then(function (response) { return response.token; });
1172
- }
1173
- /**
1174
- * Request a token for a specific application using the esri_aopc encrypted cookie
1175
- *
1176
- * When a client app boots up, it will know its clientId and the redirectUri for use
1177
- * in the normal /oauth/authorize pop-out oAuth flow.
1178
- *
1179
- * If the app sees an `esri_aopc` cookie (only set if the app is hosted on *.arcgis.com),
1180
- * it can call the /oauth2/platformSelf end-point passing in the clientId and redirectUri
1181
- * in headers, and it will receive back an app-specific token, assuming the user has
1182
- * access to the app.
1183
- *
1184
- * Since there are scenarios where an app can boot using credentials/token from localstorage
1185
- * but those credentials are not for the same user as the esri_aopc cookie, it is recommended that
1186
- * an app check the returned username against any existing identity they may have loaded.
1187
- *
1188
- * Note: This is only usable by Esri applications hosted on *arcgis.com, *esri.com or within
1189
- * an ArcGIS Enterprise installation. Custom applications can not use this.
1190
- *
1191
- * ```js
1192
- * // convert the encrypted platform cookie into a UserSession
1193
- * import { platformSelf, UserSession } from '@esri/arcgis-rest-auth';
1194
- *
1195
- * const portal = 'https://www.arcgis.com/sharing/rest';
1196
- * const clientId = 'YOURAPPCLIENTID';
1197
- *
1198
- * // exchange esri_aopc cookie
1199
- * return platformSelf(clientId, 'https://your-app-redirect-uri', portal)
1200
- * .then((response) => {
1201
- * const currentTimestamp = new Date().getTime();
1202
- * const tokenExpiresTimestamp = currentTimestamp + (response.expires_in * 1000);
1203
- * // Construct the session and return it
1204
- * return new UserSession({
1205
- * portal,
1206
- * clientId,
1207
- * username: response.username,
1208
- * token: response.token,
1209
- * tokenExpires: new Date(tokenExpiresTimestamp),
1210
- * ssl: true
1211
- * });
1212
- * })
1213
- *
1214
- * ```
1215
- *
1216
- *
1217
- * @param clientId
1218
- * @param redirectUri
1219
- * @param portal
1220
- */
1221
- function platformSelf(clientId, redirectUri, portal) {
1222
- if (portal === void 0) { portal = "https://www.arcgis.com/sharing/rest"; }
1223
- // TEMPORARY: the f=json should not be needed, but currently is
1224
- var url = portal + "/oauth2/platformSelf?f=json";
1225
- var ro = {
1226
- method: "POST",
1227
- headers: {
1228
- "X-Esri-Auth-Client-Id": clientId,
1229
- "X-Esri-Auth-Redirect-Uri": redirectUri,
1230
- },
1231
- // Note: request has logic to include the cookie
1232
- // for platformSelf calls w/ the X-Esri-Auth-Client-Id header
1233
- params: {
1234
- f: "json",
1235
- },
1236
- };
1237
- // make the request and return the token
1238
- return arcgisRestRequest.request(url, ro);
1239
- }
1240
-
1241
- exports.ApiKey = ApiKey;
1242
- exports.ApplicationSession = ApplicationSession;
1243
- exports.UserSession = UserSession;
1244
- exports.exchangeToken = exchangeToken;
1245
- exports.fetchToken = fetchToken;
1246
- exports.generateToken = generateToken;
1247
- exports.platformSelf = platformSelf;
1248
- exports.validateAppAccess = validateAppAccess;
1249
-
1250
- Object.defineProperty(exports, '__esModule', { value: true });
1251
-
1252
- })));
1253
- //# sourceMappingURL=auth.umd.js.map