/
authentication.service.ts
55 lines (43 loc) · 1.69 KB
/
authentication.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
import { Injectable } from '@angular/core';
import { AuthConfig, OAuthService } from 'angular-oauth2-oidc';
import { BehaviorSubject, from, Observable } from 'rxjs';
import { StatehandlerService } from './statehandler.service';
@Injectable({
providedIn: 'root',
})
export class AuthenticationService {
private _authenticated: boolean = false;
private readonly _authenticationChanged: BehaviorSubject<boolean> = new BehaviorSubject(this.authenticated);
constructor(
private oauthService: OAuthService,
private authConfig: AuthConfig,
private statehandler: StatehandlerService,
) {}
public get authenticated(): boolean {
return this._authenticated;
}
public get authenticationChanged(): Observable<boolean> {
return this._authenticationChanged;
}
public getOIDCUser(): Observable<any> {
return from(this.oauthService.loadUserProfile());
}
public async authenticate(setState: boolean = true): Promise<boolean> {
this.oauthService.configure(this.authConfig);
this.oauthService.setupAutomaticSilentRefresh();
this.oauthService.strictDiscoveryDocumentValidation = false;
await this.oauthService.loadDiscoveryDocumentAndTryLogin();
this._authenticated = this.oauthService.hasValidAccessToken();
if (!this.oauthService.hasValidIdToken() || !this.authenticated) {
const newState = setState ? await this.statehandler.createState().toPromise() : undefined;
this.oauthService.initCodeFlow(newState);
}
this._authenticationChanged.next(this.authenticated);
return this.authenticated;
}
public signout(): void {
this.oauthService.logOut();
this._authenticated = false;
this._authenticationChanged.next(false);
}
}