-
Notifications
You must be signed in to change notification settings - Fork 119
/
UserSession.ts
755 lines (669 loc) · 21 KB
/
UserSession.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
* Apache-2.0 */
import * as http from "http";
import {
request,
ArcGISAuthError,
IAuthenticationManager
} from "@esri/arcgis-rest-request";
import { generateToken } from "./generate-token";
import { fetchToken, IFetchTokenResponse } from "./fetch-token";
import { IUser } from "@esri/arcgis-rest-common-types";
/**
* Internal utility for resolving a Promise from outside its constructor.
*
* See: http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/
*/
interface IDeferred<T> {
promise: Promise<T>;
resolve: (v: T) => void;
reject: (v: any) => void;
}
/**
* Represents a [credential]((https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-Credential.html)) object used to access a secure ArcGIS resource.
*/
export interface ICredential {
expires: number;
server: string;
ssl: boolean;
token: string;
userId: string;
}
function defer<T>(): IDeferred<T> {
const deferred: any = {
promise: null,
resolve: null,
reject: null
};
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred as IDeferred<T>;
}
/**
* Options for static OAuth 2.0 helper methods on `UserSession`.
*/
export interface IOauth2Options {
/**
* Client ID of your application. Can be obtained by registering an application
* on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),
* [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
clientId: string;
/**
* A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),
* [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
redirectUri: string;
/**
* The ArcGIS Online or ArcGIS Enterprise portal you want to use for authentication. Defaults to `https://www.arcgis.com/sharing/rest` for the ArcGIS Online portal.
*/
portal?: string;
/**
* Duration (in minutes) that a token will be valid. Defaults to 20160 (two weeks).
*/
duration?: number;
/**
* Determines whether to open the authorization window in a new tab/window or in the current window.
*
* @browserOnly
*/
popup?: boolean;
/**
* Duration (in minutes) that a refresh token will be valid.
*
* @nodeOnly
*/
refreshTokenTTL?: number;
/**
* The locale assumed to render the login page.
*
* @browserOnly
*/
locale?: string;
/**
* Applications can specify an opaque value for this parameter to correlate the authorization request sent with the received response. By default, clientId is used.
*
* @browserOnly
*/
state?: string;
}
/**
* Options for the `UserSession` constructor.
*/
export interface IUserSessionOptions {
/**
* Client ID of your application. Can be obtained by registering an application
* on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),
* [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
clientId?: string;
/**
* A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),
* [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
redirectUri?: string;
/**
* OAuth 2.0 refresh token from a previous user session.
*/
refreshToken?: string;
/**
* Expiration date of the `refreshToken`
*/
refreshTokenExpires?: Date;
/**
* The authenticated user's username. Guaranteed to be unique across ArcGIS Online or your instance of ArcGIS Enterprise.
*/
username?: string;
/**
* Password for this user. Used in CLI apps where users cannot do OAuth 2.0.
*/
password?: string;
/**
* OAuth 2.0 access token from a previous user session.
*/
token?: string;
/**
* Expiration date for the `token`
*/
tokenExpires?: Date;
/**
* The ArcGIS Online or ArcGIS Enterprise portal you want to use for authentication. Defaults to `https://www.arcgis.com/sharing/rest` for the ArcGIS Online portal.
*/
portal?: string;
/**
* Duration of requested token validity in minutes. Used when requesting tokens with `username` and `password` or when validating the identity of unknown servers. Defaults to two weeks.
*/
tokenDuration?: number;
/**
* Duration (in minutes) that a refresh token will be valid.
*/
refreshTokenTTL?: number;
}
/**
* ```js
* const session = new UserSession({
* username: "jsmith",
* password: "123456"
* })
* ```
* 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.
*
*/
export class UserSession implements IAuthenticationManager {
/**
* Client ID being used for authentication if provided in the `constructor`.
*/
readonly clientId: string;
/**
* The currently authenticated user if provided in the `constructor`.
*/
readonly username: string;
/**
* The currently authenticated user's password if provided in the `constructor`.
*/
readonly password: string;
/**
* The current portal the user is authenticated with.
*/
readonly portal: string;
/**
* Determines how long new tokens requested are valid.
*/
readonly tokenDuration: number;
/**
* A valid redirect URI for this application if provided in the `constructor`.
*/
readonly redirectUri: string;
/**
* Duration of new OAuth 2.0 refresh token validity.
*/
readonly refreshTokenTTL: number;
/**
* Hydrated by a call to [getUser()](#getUser-summary).
*/
_user: IUser;
private _token: string;
private _tokenExpires: Date;
private _refreshToken: string;
private _refreshTokenExpires: Date;
/**
* Internal object to keep track of pending token requests. Used to prevent
* duplicate token requests.
*/
private _pendingTokenRequests: {
[key: string]: Promise<string>;
};
/**
* Internal list of trusted 3rd party servers (federated servers) that have
* been validated with `generateToken`.
*/
private trustedServers: {
[key: string]: {
token: string;
expires: Date;
};
};
/**
* The current ArcGIS Online or ArcGIS Enterprise `token`.
*/
get token() {
return this._token;
}
/**
* The expiration time of the current `token`.
*/
get tokenExpires() {
return this._tokenExpires;
}
/**
* The current token to ArcGIS Online or ArcGIS Enterprise.
*/
get refreshToken() {
return this._refreshToken;
}
/**
* The expiration time of the current `refreshToken`.
*/
get refreshTokenExpires() {
return this._refreshTokenExpires;
}
constructor(options: IUserSessionOptions) {
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 = {};
}
/**
* Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is true the
* authentication window will open in a new tab/window otherwise the user will
* be redirected to the authorization page in their current tab.
*
* @browserOnly
*/
/* istanbul ignore next */
static beginOAuth2(options: IOauth2Options, win: any = window) {
const {
portal,
clientId,
duration,
redirectUri,
popup,
state,
locale
}: IOauth2Options = {
...{
portal: "https://arcgis.com/sharing/rest",
duration: 20160,
popup: true,
state: options.clientId,
locale: ""
},
...options
};
const url = `${portal}/oauth2/authorize?client_id=${clientId}&response_type=token&expiration=${duration}&redirect_uri=${encodeURIComponent(
redirectUri
)}&state=${state}&locale=${locale}`;
if (!popup) {
win.location.href = url;
return undefined;
}
const session = defer<UserSession>();
win[`__ESRI_REST_AUTH_HANDLER_${clientId}`] = function(
errorString: any,
oauthInfoString: string
) {
if (errorString) {
const error = JSON.parse(errorString);
session.reject(new ArcGISAuthError(error.errorMessage, error.error));
return;
}
if (oauthInfoString) {
const oauthInfo = JSON.parse(oauthInfoString);
session.resolve(
new UserSession({
clientId,
portal,
token: oauthInfo.token,
tokenExpires: new Date(oauthInfo.expires),
username: oauthInfo.username
})
);
}
};
win.open(
url,
"oauth-window",
"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes"
);
return session.promise;
}
/**
* Completes a browser-based OAuth 2.0 sign if `options.popup` is true the user
* will be returned to the previous window. Otherwise a new `UserSession`
* will be returned.
*
* @browserOnly
*/
/* istanbul ignore next */
static completeOAuth2(options: IOauth2Options, win: any = window) {
const { portal, clientId }: IOauth2Options = {
...{ portal: "https://arcgis.com/sharing/rest" },
...options
};
function completeSignIn(error: any, oauthInfo?: IFetchTokenResponse) {
if (win.opener && win.opener.parent) {
win.opener.parent[`__ESRI_REST_AUTH_HANDLER_${clientId}`](
error ? JSON.stringify(error) : undefined,
JSON.stringify(oauthInfo)
);
win.close();
return undefined;
}
if (win !== win.parent) {
win.parent[`__ESRI_REST_AUTH_HANDLER_${clientId}`](
error ? JSON.stringify(error) : undefined,
JSON.stringify(oauthInfo)
);
win.close();
return undefined;
}
if (error) {
throw new ArcGISAuthError(error.errorMessage, error.error);
}
return new UserSession({
clientId,
portal,
token: oauthInfo.token,
tokenExpires: oauthInfo.expires,
username: oauthInfo.username
});
}
const match = win.location.href.match(
/access_token=(.+)&expires_in=(.+)&username=([^&]+)/
);
if (!match) {
const errorMatch = win.location.href.match(
/error=(.+)&error_description=(.+)/
);
const error = errorMatch[1];
const errorMessage = decodeURIComponent(errorMatch[2]);
return completeSignIn({ error, errorMessage });
}
const token = match[1];
const expires = new Date(
Date.now() + parseInt(match[2], 10) * 1000 - 60 * 1000
);
const username = decodeURIComponent(match[3]);
return completeSignIn(undefined, {
token,
expires,
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
*/
static authorize(options: IOauth2Options, response: http.ServerResponse) {
const { portal, clientId, duration, redirectUri }: IOauth2Options = {
...{ portal: "https://arcgis.com/sharing/rest", duration: 20160 },
...options
};
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
*/
static exchangeAuthorizationCode(
options: IOauth2Options,
authorizationCode: string
): Promise<UserSession> {
const {
portal,
clientId,
duration,
redirectUri,
refreshTokenTTL
}: IOauth2Options = {
...{
portal: "https://www.arcgis.com/sharing/rest",
duration: 20160,
refreshTokenTTL: 1440
},
...options
};
return fetchToken(`${portal}/oauth2/token`, {
grant_type: "authorization_code",
client_id: clientId,
redirect_uri: redirectUri,
code: authorizationCode
}).then(response => {
return new UserSession({
clientId,
portal,
redirectUri,
refreshToken: response.refreshToken,
refreshTokenTTL,
refreshTokenExpires: new Date(
Date.now() + (refreshTokenTTL - 1) * 1000
),
token: response.token,
tokenExpires: response.expires,
username: response.username
});
});
}
static deserialize(str: string) {
const 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
});
}
// returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/)
getCredential(): ICredential {
return {
expires: this.tokenExpires.getTime(),
server: this.portal,
ssl: true,
token: this.token,
userId: this.username
};
}
/**
* Returns information about the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic.
*
* ```js
* session.getUser()
* .then(response => {
* console.log(response.role); // "org_admin"
* })
* ```
*
* @returns A Promise that will resolve with the data from the response.
*/
getUser(): Promise<IUser> {
if (this._user && this._user.username === this.username) {
return new Promise(resolve => resolve(this._user));
} else {
const url = `${this.portal}/community/users/${encodeURIComponent(
this.username
)}`;
return request(url, {
httpMethod: "GET",
authentication: this
}).then(response => {
this._user = response;
return response;
});
}
}
/**
* Gets an appropriate token for the given URL. If `portal` is ArcGIS Online and
* the request is to an ArcGIS Online domain `token` will be used. If the request
* is to the current `portal` the current `token` will also be used. However if
* the request is to an unknown server we will validate the server with a request
* to our current `portal`.
*/
getToken(url: string) {
if (
(/^https?:\/\/www\.arcgis\.com\/sharing\/rest\/?/.test(this.portal),
/^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);
}
}
toJSON(): IUserSessionOptions {
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
};
}
serialize() {
return JSON.stringify(this);
}
/**
* Manually refreshes the current `token` and `tokenExpires`.
*/
refreshSession(): Promise<UserSession> {
if (this.username && this.password) {
return this.refreshWithUsernameAndPassword();
}
if (this.clientId && this.refreshToken) {
return this.refreshWithRefreshToken();
}
return Promise.reject(new 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.
*/
private getTokenForServer(url: string) {
const [root] = url.split("/rest/services/");
const 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] = request(`${root}/rest/info`)
.then((response: any) => {
return response.owningSystemUrl;
})
.then(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 ArcGISAuthError(
`${url} is not federated with ${this.portal}.`,
"NOT_FEDERATED"
);
}
return request(`${owningSystemUrl}/sharing/rest/info`);
})
.then((response: any) => {
return response.authInfo.tokenServicesUrl;
})
.then((tokenServicesUrl: string) => {
return generateToken(tokenServicesUrl, {
token: this.token,
serverUrl: url,
expiration: this.tokenDuration
});
})
.then(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`.
*/
private getFreshToken() {
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(
session => {
this._pendingTokenRequests[this.portal] = null;
return session.token;
}
);
}
return this._pendingTokenRequests[this.portal];
}
/**
* Refreshes the current `token` and `tokenExpires` with `username` and
* `password`.
*/
private refreshWithUsernameAndPassword() {
return generateToken(`${this.portal}/generateToken`, {
username: this.username,
password: this.password,
expiration: this.tokenDuration
}).then((response: any) => {
this._token = response.token;
this._tokenExpires = new Date(response.expires);
return this;
});
}
/**
* Refreshes the current `token` and `tokenExpires` with `refreshToken`.
*/
private refreshWithRefreshToken() {
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(response => {
this._token = response.token;
this._tokenExpires = response.expires;
return this;
});
}
/**
* Exchanges an expired `refreshToken` for a new one also updates `token` and
* `tokenExpires`.
*/
private refreshRefreshToken() {
return fetchToken(`${this.portal}/oauth2/token`, {
client_id: this.clientId,
refresh_token: this.refreshToken,
redirect_uri: this.redirectUri,
grant_type: "exchange_refresh_token"
}).then(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;
});
}
}