Newer
Older
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
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { AccountService } from './account.service';
@Injectable()
export class Principal {
private userIdentity: any;
private authenticated = false;
private authenticationState = new Subject<any>();
constructor(
private account: AccountService
) {}
authenticate(identity) {
this.userIdentity = identity;
this.authenticated = identity !== null;
this.authenticationState.next(this.userIdentity);
}
hasAnyAuthority(authorities: string[]): Promise<boolean> {
return Promise.resolve(this.hasAnyAuthorityDirect(authorities));
}
hasAnyAuthorityDirect(authorities: string[]): boolean {
if (!this.authenticated || !this.userIdentity || !this.userIdentity.authorities) {
return false;
}
for (let i = 0; i < authorities.length; i++) {
if (this.userIdentity.authorities.includes(authorities[i])) {
return true;
}
}
return false;
}
hasAuthority(authority: string): Promise<boolean> {
if (!this.authenticated) {
return Promise.resolve(false);
}
return this.identity().then((id) => {
return Promise.resolve(id.authorities && id.authorities.includes(authority));
}, () => {
return Promise.resolve(false);
});
}
identity(force?: boolean): Promise<any> {
if (force === true) {
this.userIdentity = undefined;
}
if (this.userIdentity) {
return Promise.resolve(this.userIdentity);
}
// retrieve the userIdentity data from the server, update the identity object, and then resolve.
return this.account.get().toPromise().then((response) => {
const account = response.body;
if (account) {
this.userIdentity = account;
if (this.userIdentity.authorities.length > 0) {
this.authenticated = true;
}else {
this.authenticated = false;
}
} else {
this.userIdentity = null;
this.authenticated = false;
}
this.authenticationState.next(this.userIdentity);
return this.userIdentity;
}).catch((err) => {
this.userIdentity = null;
this.authenticated = false;
this.authenticationState.next(this.userIdentity);
return null;
});
}
isAuthenticated(): boolean {
return this.authenticated;
}
isIdentityResolved(): boolean {
return this.userIdentity !== undefined;
}
getAuthenticationState(): Observable<any> {
return this.authenticationState.asObservable();
}
getImageUrl(): String {
return this.isIdentityResolved() ? this.userIdentity.imageUrl : null;
}
}