-
Notifications
You must be signed in to change notification settings - Fork 387
/
auth.service.ts
427 lines (387 loc) · 13.8 KB
/
auth.service.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
import { Inject, Injectable, Optional } from '@angular/core';
import { PRIMARY_OUTLET, Router, UrlSegmentGroup, UrlTree } 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 { distinctUntilChanged, filter, map, startWith, switchMap, take, withLatestFrom } from 'rxjs/operators';
import { RouterReducerState } from '@ngrx/router-store';
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-v2/dspace-rest-v2.service';
import { AuthStatus } from './models/auth-status.model';
import { AuthTokenInfo, TOKENITEM } from './models/auth-token-info.model';
import { isEmpty, isNotEmpty, isNotNull, isNotUndefined } from '../../shared/empty.util';
import { CookieService } from '../services/cookie.service';
import { getAuthenticationToken, getRedirectUrl, isAuthenticated, isTokenRefreshing } from './selectors';
import { AppState, routerStateSelector } from '../../app.reducer';
import { ResetAuthenticationMessagesAction, SetRedirectUrlAction } from './auth.actions';
import { NativeWindowRef, NativeWindowService } from '../services/window.service';
import { Base64EncodeUrl } from '../../shared/utils/encode-decode.util';
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
import {RouteService} from '../services/route.service';
export const LOGIN_ROUTE = '/login';
export const LOGOUT_ROUTE = '/logout';
export const REDIRECT_COOKIE = 'dsRedirectUrl';
/**
* The auth service.
*/
@Injectable()
export class AuthService {
/**
* True if authenticated
* @type boolean
*/
protected _authenticated: boolean;
constructor(@Inject(REQUEST) protected req: any,
@Inject(NativeWindowService) protected _window: NativeWindowRef,
protected authRequestService: AuthRequestService,
@Optional() @Inject(RESPONSE) private response: any,
protected router: Router,
protected routeService: RouteService,
protected storage: CookieService,
protected store: Store<AppState>,
protected rdbService: RemoteDataBuildService
) {
this.store.pipe(
select(isAuthenticated),
startWith(false)
).subscribe((authenticated: boolean) => this._authenticated = authenticated);
// If current route is different from the one setted in authentication guard
// and is not the login route, clear redirect url and messages
const routeUrl$ = this.store.pipe(
select(routerStateSelector),
filter((routerState: RouterReducerState) => isNotUndefined(routerState) && isNotUndefined(routerState.state)),
filter((routerState: RouterReducerState) => !this.isLoginRoute(routerState.state.url)),
map((routerState: RouterReducerState) => routerState.state.url)
);
const redirectUrl$ = this.store.pipe(select(getRedirectUrl), distinctUntilChanged());
routeUrl$.pipe(
withLatestFrom(redirectUrl$),
map(([routeUrl, redirectUrl]) => [routeUrl, redirectUrl])
).pipe(filter(([routeUrl, redirectUrl]) => isNotEmpty(redirectUrl) && (routeUrl !== redirectUrl)))
.subscribe(() => {
this.clearRedirectUrl();
});
}
/**
* Check if is a login page route
*
* @param {string} url
* @returns {Boolean}.
*/
protected isLoginRoute(url: string) {
const urlTree: UrlTree = this.router.parseUrl(url);
const g: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
const segment = '/' + g.toString();
return segment === LOGIN_ROUTE;
}
/**
* 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=${Base64EncodeUrl(password)}&user=${Base64EncodeUrl(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((status: AuthStatus) => {
if (status.authenticated) {
return status;
} else {
throw(new Error('Invalid email or password'));
}
}))
}
/**
* Determines if the user is authenticated
* @returns {Observable<boolean>}
*/
public isAuthenticated(): Observable<boolean> {
return this.store.pipe(select(isAuthenticated));
}
/**
* Returns the authenticated user
* @returns {User}
*/
public authenticatedUser(token: AuthTokenInfo): Observable<EPerson> {
// 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((status) => this.rdbService.build(status)),
switchMap((status: AuthStatus) => {
if (status.authenticated) {
return status.eperson.pipe(map((eperson) => eperson.payload));
} else {
throw(new Error('Not authenticated'));
}
}))
}
/**
* Checks if token is present into browser storage and is valid. (NB Check is done only on SSR)
*/
public checkAuthenticationToken() {
return
}
/**
* 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');
headers = headers.append('Authorization', `Bearer ${token.accessToken}`);
options.headers = headers;
return this.authRequestService.postToEndpoint('login', {}, options).pipe(
map((status: AuthStatus) => {
if (status.authenticated) {
return status.token;
} else {
throw(new Error('Not authenticated'));
}
}));
}
/**
* Clear authentication errors
*/
public resetAuthenticationError(): void {
this.store.dispatch(new ResetAuthenticationMessagesAction());
}
/**
* Create a new user
* @returns {User}
*/
public create(user: EPerson): Observable<EPerson> {
// Normally you would do an HTTP request to POST the user
// details and then return the new user object
// but, let's just return the new user for this example.
// this._authenticated = true;
return observableOf(user);
}
/**
* 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.getRequest('logout', options).pipe(
map((status: AuthStatus) => {
if (!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(select(getAuthenticationToken))
.subscribe((authTokenInfo: AuthTokenInfo) => {
// Retrieve authentication token info and check if is valid
token = authTokenInfo || null;
});
return token;
}
/**
* 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);
}
}
/**
* Redirect to the route navigated before the login
*/
public redirectAfterLoginSuccess(isStandalonePage: boolean) {
this.getRedirectUrl().pipe(
take(1))
.subscribe((redirectUrl) => {
if (isNotEmpty(redirectUrl)) {
this.clearRedirectUrl();
this.router.onSameUrlNavigation = 'reload';
this.navigateToRedirectUrl(redirectUrl);
} else {
// If redirectUrl is empty use history.
this.routeService.getHistory().pipe(
take(1)
).subscribe((history) => {
let redirUrl;
if (isStandalonePage) {
// For standalone login pages, use the previous route.
redirUrl = history[history.length - 2] || '';
} else {
redirUrl = history[history.length - 1] || '';
}
this.navigateToRedirectUrl(redirUrl);
});
}
});
}
protected navigateToRedirectUrl(redirectUrl: string) {
const url = decodeURIComponent(redirectUrl);
// in case the user navigates directly to /login (via bookmark, etc), or the route history is not found.
if (isEmpty(url) || url.startsWith(LOGIN_ROUTE)) {
this.router.navigateByUrl('/');
/* TODO Reenable hard redirect when REST API can handle x-forwarded-for, see https://github.com/DSpace/DSpace/pull/2207 */
// this._window.nativeWindow.location.href = '/';
} else {
/* TODO Reenable hard redirect when REST API can handle x-forwarded-for, see https://github.com/DSpace/DSpace/pull/2207 */
// this._window.nativeWindow.location.href = url;
this.router.navigateByUrl(url);
}
}
/**
* Refresh route navigated
*/
public refreshAfterLogout() {
this.router.navigate(['/home']);
// Hard redirect to home page, so that all state is definitely lost
this._window.nativeWindow.location.href = '/home';
}
/**
* Get redirect url
*/
getRedirectUrl(): Observable<string> {
const redirectUrl = this.storage.get(REDIRECT_COOKIE);
if (isNotEmpty(redirectUrl)) {
return observableOf(redirectUrl);
} else {
return this.store.pipe(select(getRedirectUrl));
}
}
/**
* 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 : ''));
}
/**
* Clear redirect url
*/
clearRedirectUrl() {
this.store.dispatch(new SetRedirectUrlAction(''));
this.storage.remove(REDIRECT_COOKIE);
}
}