-
Notifications
You must be signed in to change notification settings - Fork 2
/
AuthAzure.ts
105 lines (84 loc) · 3.08 KB
/
AuthAzure.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
import { AuthenticationResult, IPublicClientApplication, PublicClientApplication } from '@azure/msal-browser';
import { Client } from '@microsoft/microsoft-graph-client';
import { loginRequest, msalConfig } from '../../services/azure.config';
import { User, AuthMethodKey } from './auth.model';
import { IAuth } from './IAuth';
export class AuthAzure implements IAuth {
public type: AuthMethodKey = 'AZURE';
private instance: PublicClientApplication;
constructor(){
this.instance = new PublicClientApplication(msalConfig);
console.log('starting auth azure');
}
public signIn = async () => {
console.log('signIn azure');
await this.instance.handleRedirectPromise().then(() => {
this.handleLogin(this.instance);
});
};
public signOut = async () => {
console.log('signOut azure');
await this.instance.handleRedirectPromise().then(() => {
this.handleLogout(this.instance);
});
};
public isAuthenticated = async () => {
return await this.instance.handleRedirectPromise().then(x => {
const accounts = this.instance.getAllAccounts();
return accounts.length > 0;
});
};
public getUser = async () => {
const userStorage = localStorage.getItem('@Auth.user');
if(userStorage !== null) {
return JSON.parse(userStorage) as User;
}
const accounts = this.instance.getAllAccounts();
if(accounts.length === 0) {
return undefined;
}
const request = {
...loginRequest,
account: accounts[0]
};
// Silently acquires an access token which is then attached to a request for Microsoft Graph data
const userAzure = await this.instance.acquireTokenSilent(request).then((response: AuthenticationResult) => {
return this.getUserDetails(response.accessToken);
});
if(userAzure) {
const user = {
email: userAzure.userPrincipalName,
username: userAzure.displayName
} as User;
localStorage.setItem('@Auth.user', JSON.stringify(user));
return user;
}
return undefined;
}
private getAuthenticatedClient = (accessToken: string) => {
const client = Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
return client;
}
private getUserDetails = async (accessToken: string) => {
const client = this.getAuthenticatedClient(accessToken);
const user = await client
.api('/me')
.select('displayName,mail,userPrincipalName')
.get();
return user;
}
private handleLogin = (instance: IPublicClientApplication) => {
instance.loginRedirect(loginRequest).catch(e => {
console.error(e);
});
}
private handleLogout = (instance: IPublicClientApplication) => {
instance.logout().catch(e => {
console.error(e);
});
}
}