/
V2Provider.ts
69 lines (55 loc) 路 2 KB
/
V2Provider.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
import { UserAgentApplication } from 'msal';
import { IAuthProvider, ProviderType, LoginChangedEvent } from "./IAuthProvider";
import { Graph } from './GraphSDK';
import { EventHandler, EventDispatcher } from './EventHandler';
export class V2Provider implements IAuthProvider {
private _loginChangedDispatcher = new EventDispatcher<LoginChangedEvent>();
readonly type: ProviderType;
readonly provider: any;
scopes: string[];
graph: Graph;
constructor(clientId: string, scopes: string[] = ["user.read"], authority: string = null, options: any = null) {
this.type = ProviderType.V2;
this.provider = new UserAgentApplication(clientId, authority, this.tokenReceivedCallback);
this.scopes = scopes;
}
async login(): Promise<void> {
let provider = this.provider as UserAgentApplication;
let token = await provider.loginPopup(this.scopes);
if (token) {
await this.loginSilent();
}
}
async loginSilent(): Promise<boolean> {
let provider = this.provider as UserAgentApplication;
try {
let accessToken = await provider.acquireTokenSilent(this.scopes);
if (accessToken) {
this.graph = new Graph(accessToken);
this.fireLoginChangedEvent({});
return true;
}
} catch {
return false;
}
return false;
}
async logout(): Promise<void> {
let provider = this.provider as UserAgentApplication;
provider.logout();
this.fireLoginChangedEvent({});
}
updateScopes(scopes: string[]) {
this.scopes = scopes;
}
tokenReceivedCallback(token : any)
{
return token;
}
onLoginChanged(eventHandler : EventHandler<LoginChangedEvent>) {
this._loginChangedDispatcher.register(eventHandler);
}
private fireLoginChangedEvent(event : LoginChangedEvent) {
this._loginChangedDispatcher.fire(event);
}
}