-
Notifications
You must be signed in to change notification settings - Fork 6
/
auth.guard.ts
58 lines (53 loc) · 1.85 KB
/
auth.guard.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
import { Inject, Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { DOCUMENT } from '@angular/common';
import { Actions, ofActionCompleted, Select, Store } from '@ngxs/store';
import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ReadUser } from '@dasch-swiss/dsp-js';
import { AuthService } from '@dasch-swiss/vre/shared/app-session';
import {
CurrentPageSelectors,
SetUserAction,
UserSelectors,
} from '@dasch-swiss/vre/shared/app-state';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
@Select(UserSelectors.user) user$: Observable<ReadUser>;
constructor(
private store: Store,
private _authService: AuthService,
private actions$: Actions,
@Inject(DOCUMENT) private document: Document
) {}
canActivate(): Observable<boolean> {
return this.user$.pipe(
switchMap((user) => {
if (user) return of(null);
if (this.store.selectSnapshot(UserSelectors.isLoading)) {
return this.actions$.pipe(ofActionCompleted(SetUserAction));
} else {
return this.store.dispatch(new SetUserAction(user));
}
}),
switchMap(() => this._authService.isLoggedIn$),
map((isLoggedIn) => {
if (isLoggedIn) {
return true;
} else {
this._goToHomePage();
return false;
}
})
);
}
private _goToHomePage() {
this.document.defaultView.location.href =
`${this.document.defaultView.location.href}?` +
`returnLink=${this.store.selectSnapshot(
CurrentPageSelectors.loginReturnLink
)}`;
}
}