forked from DSpace/dspace-angular
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.service.ts
More file actions
613 lines (559 loc) · 18.7 KB
/
auth.service.ts
File metadata and controls
613 lines (559 loc) · 18.7 KB
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
import { Inject, Injectable, Optional } from '@angular/core';
import { Params, Router } from '@angular/router';
import { HttpHeaders } from '@angular/common/http';
import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';
import { Observable, of as observableOf } from 'rxjs';
import { map, startWith, switchMap, take } from 'rxjs/operators';
import { select, Store } from '@ngrx/store';
import { CookieAttributes } from 'js-cookie';
import { EPerson } from '../eperson/models/eperson.model';
import { AuthRequestService } from './auth-request.service';
import { HttpOptions } from '../dspace-rest/dspace-rest.service';
import { AuthStatus } from './models/auth-status.model';
import { AuthTokenInfo, TOKENITEM } from './models/auth-token-info.model';
import {
hasNoValue,
hasValue,
hasValueOperator,
isEmpty,
isNotEmpty,
isNotNull,
isNotUndefined
} from '../../shared/empty.util';
import { CookieService } from '../services/cookie.service';
import {
getAuthenticatedUserId,
getAuthenticationToken,
getRedirectUrl,
isAuthenticated,
isAuthenticatedLoaded,
isIdle,
isTokenRefreshing
} from './selectors';
import { AppState } from '../../app.reducer';
import {
CheckAuthenticationTokenAction,
RefreshTokenAction,
ResetAuthenticationMessagesAction,
SetRedirectUrlAction,
SetUserAsIdleAction,
UnsetUserAsIdleAction
} from './auth.actions';
import { NativeWindowRef, NativeWindowService } from '../services/window.service';
import { RouteService } from '../services/route.service';
import { EPersonDataService } from '../eperson/eperson-data.service';
import { getAllSucceededRemoteDataPayload } from '../shared/operators';
import { AuthMethod } from './models/auth.method';
import { HardRedirectService } from '../services/hard-redirect.service';
import { RemoteData } from '../data/remote-data';
import { environment } from '../../../environments/environment';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { TranslateService } from '@ngx-translate/core';
import { MISSING_HEADERS_FROM_IDP_EXCEPTION, USER_WITHOUT_EMAIL_EXCEPTION } from '../shared/clarin/constants';
export const LOGIN_ROUTE = '/login';
export const LOGOUT_ROUTE = '/logout';
export const REDIRECT_COOKIE = 'dsRedirectUrl';
export const IMPERSONATING_COOKIE = 'dsImpersonatingEPerson';
/**
* The auth service.
*/
@Injectable()
export class AuthService {
/**
* True if authenticated
* @type boolean
*/
protected _authenticated: boolean;
/**
* Timer to track time until token refresh
*/
private tokenRefreshTimer;
constructor(@Inject(REQUEST) protected req: any,
@Inject(NativeWindowService) protected _window: NativeWindowRef,
@Optional() @Inject(RESPONSE) private response: any,
protected authRequestService: AuthRequestService,
protected epersonService: EPersonDataService,
protected router: Router,
protected routeService: RouteService,
protected storage: CookieService,
protected store: Store<AppState>,
protected hardRedirectService: HardRedirectService,
private notificationService: NotificationsService,
private translateService: TranslateService
) {
this.store.pipe(
select(isAuthenticated),
startWith(false)
).subscribe((authenticated: boolean) => this._authenticated = authenticated);
}
/**
* Authenticate the user
*
* @param {string} user The user name
* @param {string} password The user's password
* @returns {Observable<User>} The authenticated user observable.
*/
public authenticate(user: string, password: string): Observable<AuthStatus> {
// Attempt authenticating the user using the supplied credentials.
const body = (`password=${encodeURIComponent(password)}&user=${encodeURIComponent(user)}`);
const options: HttpOptions = Object.create({});
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
options.headers = headers;
return this.authRequestService.postToEndpoint('login', body, options).pipe(
map((rd: RemoteData<AuthStatus>) => {
if (hasValue(rd.payload) && rd.payload.authenticated) {
return rd.payload;
} else {
throw(new Error('Invalid email or password'));
}
}));
}
/**
* Checks if token is present into the request cookie
*/
public checkAuthenticationCookie(): Observable<AuthStatus> {
// Determine if the user has an existing auth session on the server
const options: HttpOptions = Object.create({});
let headers = new HttpHeaders();
headers = headers.append('Accept', 'application/json');
options.headers = headers;
options.withCredentials = true;
return this.authRequestService.getRequest('status', options).pipe(
map((rd: RemoteData<AuthStatus>) => Object.assign(new AuthStatus(), rd.payload))
);
}
/**
* Determines if the user is authenticated
* @returns {Observable<boolean>}
*/
public isAuthenticated(): Observable<boolean> {
return this.store.pipe(select(isAuthenticated));
}
/**
* Determines if authentication is loaded
* @returns {Observable<boolean>}
*/
public isAuthenticationLoaded(): Observable<boolean> {
return this.store.pipe(select(isAuthenticatedLoaded));
}
/**
* Returns the href link to authenticated user
* @returns {string}
*/
public authenticatedUser(token: AuthTokenInfo): Observable<string> {
// Determine if the user has an existing auth session on the server
const options: HttpOptions = Object.create({});
let headers = new HttpHeaders();
headers = headers.append('Accept', 'application/json');
headers = headers.append('Authorization', `Bearer ${token.accessToken}`);
options.headers = headers;
return this.authRequestService.getRequest('status', options).pipe(
map((rd: RemoteData<AuthStatus>) => {
const status = rd.payload;
if (hasValue(status) && status.authenticated) {
return status._links.eperson.href;
} else {
throw(new Error('Not authenticated'));
}
}));
}
/**
* Returns the authenticated user by href
* @returns {User}
*/
public retrieveAuthenticatedUserByHref(userHref: string): Observable<EPerson> {
return this.epersonService.findByHref(userHref).pipe(
getAllSucceededRemoteDataPayload()
);
}
/**
* Returns the authenticated user by id
* @returns {User}
*/
public retrieveAuthenticatedUserById(userId: string): Observable<EPerson> {
return this.epersonService.findById(userId).pipe(
getAllSucceededRemoteDataPayload()
);
}
/**
* Returns the authenticated user from the store
* @returns {User}
*/
public getAuthenticatedUserFromStore(): Observable<EPerson> {
return this.store.pipe(
select(getAuthenticatedUserId),
hasValueOperator(),
switchMap((id: string) => this.epersonService.findById(id)),
getAllSucceededRemoteDataPayload()
);
}
/**
* Checks if token is present into browser storage and is valid.
*/
public checkAuthenticationToken() {
this.store.dispatch(new CheckAuthenticationTokenAction());
}
/**
* Checks if token is present into storage and is not expired
*/
public hasValidAuthenticationToken(): Observable<AuthTokenInfo> {
return this.store.pipe(
select(getAuthenticationToken),
take(1),
map((authTokenInfo: AuthTokenInfo) => {
let token: AuthTokenInfo;
// Retrieve authentication token info and check if is valid
token = isNotEmpty(authTokenInfo) ? authTokenInfo : this.storage.get(TOKENITEM);
if (isNotEmpty(token) && token.hasOwnProperty('accessToken') && isNotEmpty(token.accessToken) && !this.isTokenExpired(token)) {
return token;
} else {
throw false;
}
})
);
}
/**
* Checks if token is present into storage
*/
public refreshAuthenticationToken(token: AuthTokenInfo): Observable<AuthTokenInfo> {
const options: HttpOptions = Object.create({});
let headers = new HttpHeaders();
headers = headers.append('Accept', 'application/json');
if (token && token.accessToken) {
headers = headers.append('Authorization', `Bearer ${token.accessToken}`);
}
options.headers = headers;
options.withCredentials = true;
return this.authRequestService.postToEndpoint('login', {}, options).pipe(
map((rd: RemoteData<AuthStatus>) => {
const status = rd.payload;
if (hasValue(status) && status.authenticated) {
return status.token;
} else {
throw(new Error('Not authenticated'));
}
}));
}
/**
* Clear authentication errors
*/
public resetAuthenticationError(): void {
this.store.dispatch(new ResetAuthenticationMessagesAction());
}
/**
* Retrieve authentication methods available
* @returns {User}
*/
public retrieveAuthMethodsFromAuthStatus(status: AuthStatus): Observable<AuthMethod[]> {
let authMethods: AuthMethod[] = [];
if (isNotEmpty(status.authMethods)) {
authMethods = status.authMethods;
}
return observableOf(authMethods);
}
/**
* End session
* @returns {Observable<boolean>}
*/
public logout(): Observable<boolean> {
// Send a request that sign end the session
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
const options: HttpOptions = Object.create({ headers, responseType: 'text' });
return this.authRequestService.postToEndpoint('logout', options).pipe(
map((rd: RemoteData<AuthStatus>) => {
const status = rd.payload;
if (hasValue(status) && !status.authenticated) {
return true;
} else {
throw(new Error('auth.errors.invalid-user'));
}
}));
}
/**
* Retrieve authentication token info and make authorization header
* @returns {string}
*/
public buildAuthHeader(token?: AuthTokenInfo): string {
if (isEmpty(token)) {
token = this.getToken();
}
return (this._authenticated && isNotNull(token)) ? `Bearer ${token.accessToken}` : '';
}
/**
* Get authentication token info
* @returns {AuthTokenInfo}
*/
public getToken(): AuthTokenInfo {
let token: AuthTokenInfo;
this.store.pipe(take(1), select(getAuthenticationToken))
.subscribe((authTokenInfo: AuthTokenInfo) => {
// Retrieve authentication token info and check if is valid
token = authTokenInfo || null;
});
return token;
}
/**
* Method that checks when the session token from store expires and refreshes it when needed
*/
public trackTokenExpiration(): void {
let token: AuthTokenInfo;
let currentlyRefreshingToken = false;
this.store.pipe(select(getAuthenticationToken)).subscribe((authTokenInfo: AuthTokenInfo) => {
// If new token is undefined an it wasn't previously => Refresh failed
if (currentlyRefreshingToken && token !== undefined && authTokenInfo === undefined) {
// Token refresh failed => Error notification => 10 second wait => Page reloads & user logged out
this.notificationService.error(this.translateService.get('auth.messages.token-refresh-failed'));
setTimeout(() => this.navigateToRedirectUrl(this.hardRedirectService.getCurrentRoute()), 10000);
currentlyRefreshingToken = false;
}
// If new token.expires is different => Refresh succeeded
if (currentlyRefreshingToken && authTokenInfo !== undefined && token.expires !== authTokenInfo.expires) {
currentlyRefreshingToken = false;
}
// Check if/when token needs to be refreshed
if (!currentlyRefreshingToken) {
token = authTokenInfo || null;
if (token !== undefined && token !== null) {
let timeLeftBeforeRefresh = token.expires - new Date().getTime() - environment.auth.rest.timeLeftBeforeTokenRefresh;
if (timeLeftBeforeRefresh < 0) {
timeLeftBeforeRefresh = 0;
}
if (hasValue(this.tokenRefreshTimer)) {
clearTimeout(this.tokenRefreshTimer);
}
this.tokenRefreshTimer = setTimeout(() => {
this.store.dispatch(new RefreshTokenAction(token));
currentlyRefreshingToken = true;
}, timeLeftBeforeRefresh);
}
}
});
}
/**
* Check if a token is next to be expired
* @returns {boolean}
*/
public isTokenExpiring(): Observable<boolean> {
return this.store.pipe(
select(isTokenRefreshing),
take(1),
map((isRefreshing: boolean) => {
if (this.isTokenExpired() || isRefreshing) {
return false;
} else {
const token = this.getToken();
return token.expires - (60 * 5 * 1000) < Date.now();
}
})
);
}
/**
* Check if a token is expired
* @returns {boolean}
*/
public isTokenExpired(token?: AuthTokenInfo): boolean {
token = token || this.getToken();
return token && token.expires < Date.now();
}
/**
* Save authentication token info
*
* @param {AuthTokenInfo} token The token to save
* @returns {AuthTokenInfo}
*/
public storeToken(token: AuthTokenInfo) {
// Add 1 day to the current date
const expireDate = Date.now() + (1000 * 60 * 60 * 24);
// Set the cookie expire date
const expires = new Date(expireDate);
const options: CookieAttributes = {expires: expires};
// Save cookie with the token
return this.storage.set(TOKENITEM, token, options);
}
/**
* Remove authentication token info
*/
public removeToken() {
return this.storage.remove(TOKENITEM);
}
/**
* Replace authentication token info with a new one
*/
public replaceToken(token: AuthTokenInfo) {
this.removeToken();
return this.storeToken(token);
}
/**
* Redirect to the login route
*/
public redirectToLogin() {
this.router.navigate([LOGIN_ROUTE]);
}
/**
* Redirect to the login route when token has expired
*/
public redirectToLoginWhenTokenExpired() {
const redirectUrl = LOGIN_ROUTE + '?expired=true';
if (this._window.nativeWindow.location) {
// Hard redirect to login page, so that all state is definitely lost
this._window.nativeWindow.location.href = redirectUrl;
} else if (this.response) {
if (!this.response._headerSent) {
this.response.redirect(302, redirectUrl);
}
} else {
this.router.navigateByUrl(redirectUrl);
}
}
/**
* Perform a hard redirect to the URL
* @param redirectUrl
*/
public navigateToRedirectUrl(redirectUrl: string) {
// Don't do redirect if already on reload url
if (!hasValue(redirectUrl) || !redirectUrl.includes('/reload/')) {
let url = `/reload/${new Date().getTime()}`;
if (isNotEmpty(redirectUrl) && !redirectUrl.startsWith(LOGIN_ROUTE)) {
url += `?redirect=${encodeURIComponent(redirectUrl)}`;
}
this.hardRedirectService.redirect(url);
}
}
/**
* Refresh route navigated
*/
public refreshAfterLogout() {
this.navigateToRedirectUrl(undefined);
}
/**
* Get redirect url
*/
getRedirectUrl(): Observable<string> {
return this.store.pipe(
select(getRedirectUrl),
map((urlFromStore: string) => {
if (hasValue(urlFromStore)) {
return urlFromStore;
} else {
return this.storage.get(REDIRECT_COOKIE);
}
})
);
}
/**
* Set redirect url
*/
setRedirectUrl(url: string) {
// Add 1 hour to the current date
const expireDate = Date.now() + (1000 * 60 * 60);
// Set the cookie expire date
const expires = new Date(expireDate);
const options: CookieAttributes = {expires: expires};
this.storage.set(REDIRECT_COOKIE, url, options);
this.store.dispatch(new SetRedirectUrlAction(isNotUndefined(url) ? url : ''));
}
/**
* Set the redirect url if the current one has not been set yet
* @param newRedirectUrl
*/
setRedirectUrlIfNotSet(newRedirectUrl: string) {
this.getRedirectUrl().pipe(
take(1))
.subscribe((currentRedirectUrl) => {
if (hasNoValue(currentRedirectUrl)) {
this.setRedirectUrl(newRedirectUrl);
}
});
}
/**
* Clear redirect url
*/
clearRedirectUrl() {
this.store.dispatch(new SetRedirectUrlAction(undefined));
this.storage.remove(REDIRECT_COOKIE);
}
/**
* Start impersonating EPerson
* @param epersonId ID of the EPerson to impersonate
*/
impersonate(epersonId: string) {
this.storage.set(IMPERSONATING_COOKIE, epersonId);
this.refreshAfterLogout();
}
/**
* Stop impersonating EPerson
*/
stopImpersonating() {
this.storage.remove(IMPERSONATING_COOKIE);
}
/**
* Stop impersonating EPerson and refresh the store/ui
*/
stopImpersonatingAndRefresh() {
this.stopImpersonating();
this.refreshAfterLogout();
}
/**
* Get the ID of the EPerson we're currently impersonating
* Returns undefined if we're not impersonating anyone
*/
getImpersonateID(): string {
return this.storage.get(IMPERSONATING_COOKIE);
}
/**
* Whether or not we are currently impersonating an EPerson
*/
isImpersonating(): boolean {
return hasValue(this.getImpersonateID());
}
/**
* Whether or not we are currently impersonating a specific EPerson
* @param epersonId ID of the EPerson to check
*/
isImpersonatingUser(epersonId: string): boolean {
return this.getImpersonateID() === epersonId;
}
/**
* Get a short-lived token for appending to download urls of restricted files
* Returns null if the user isn't authenticated
*/
getShortlivedToken(): Observable<string> {
return this.isAuthenticated().pipe(
switchMap((authenticated) => authenticated ? this.authRequestService.getShortlivedToken() : observableOf(null))
);
}
/**
* Determines if current user is idle
* @returns {Observable<boolean>}
*/
public isUserIdle(): Observable<boolean> {
return this.store.pipe(select(isIdle));
}
/**
* Set idle of auth state
* @returns {Observable<boolean>}
*/
public setIdle(idle: boolean): void {
if (idle) {
this.store.dispatch(new SetUserAsIdleAction());
} else {
this.store.dispatch(new UnsetUserAsIdleAction());
}
}
/**
* From the authentication retrieve the `netid` from the error message
* @param errorMessage from the authentication request
* @private
*/
private retrieveParamsFromErrorMessage(errorMessage) {
const separator = ',';
const paramsArray = errorMessage.split(separator);
const paramObject: Params = {};
// USER_WITHOUT_EMAIL_EXCEPTION is in the 0 - it is ignored
// netid param is in the position 1
paramObject.netid = paramsArray[1];
return paramObject;
}
}