-
Notifications
You must be signed in to change notification settings - Fork 104
/
adal.service.ts
265 lines (216 loc) · 9.27 KB
/
adal.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/// <reference path="adal-angular.d.ts" />
import { Injectable, NgZone } from '@angular/core';
import { Observable, bindCallback, timer } from 'rxjs';
import { map } from 'rxjs/operators';
import * as lib from 'adal-angular';
@Injectable()
export class AdalService {
private context: adal.AuthenticationContext = <any>null;
private loginRefreshTimer = <any>null;
private user: adal.User = {
authenticated: false,
userName: '',
error: '',
token: '',
profile: {},
loginCached: false
};
constructor(private ngZone: NgZone) { }
public init(configOptions: adal.Config): void {
if (!configOptions) {
throw new Error('You must set config, when calling init.');
}
// redirect and logout_redirect are set to current location by default
const existingHash = window.location.hash;
let pathDefault = window.location.href;
if (existingHash) {
pathDefault = pathDefault.replace(existingHash, '');
}
configOptions.redirectUri = configOptions.redirectUri || pathDefault;
configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;
// create instance with given config
this.context = lib.inject(configOptions);
this.updateDataFromCache();
if (this.user.loginCached && !this.user.authenticated && window.self == window.top && !this.isInCallbackRedirectMode) {
this.refreshLoginToken();
} else if (this.user.loginCached && this.user.authenticated && !this.loginRefreshTimer && window.self == window.top) {
this.setupLoginTokenRefreshTimer();
}
}
public get config(): adal.Config {
return this.context.config;
}
public get userInfo(): adal.User {
return this.user;
}
public login(): void {
this.context.login();
}
public loginInProgress(): boolean {
return this.context.loginInProgress();
}
public logOut(): void {
this.context.logOut();
}
public handleWindowCallback(removeHash: boolean = true): void {
const hash = window.location.hash;
if (this.context.isCallback(hash)) {
var isPopup = false;
if (this.context._openedWindows.length > 0 && this.context._openedWindows[this.context._openedWindows.length - 1].opener && this.context._openedWindows[this.context._openedWindows.length - 1].opener._adalInstance) {
this.context = this.context._openedWindows[this.context._openedWindows.length - 1].opener._adalInstance;
isPopup = true;
} else {
try {
if (window.parent && window.parent._adalInstance) {
this.context = window.parent._adalInstance;
}
} catch {
// ignore any exceptions and resort to default context.
}
}
const requestInfo = this.context.getRequestInfo(hash);
this.context.saveTokenFromHash(requestInfo);
var callback = this.context._callBackMappedToRenewStates[requestInfo.stateResponse] || this.context.callback;
if (requestInfo.requestType === this.context.REQUEST_TYPE.LOGIN) {
this.updateDataFromCache();
this.setupLoginTokenRefreshTimer();
} else if (requestInfo.requestType === this.context.REQUEST_TYPE.RENEW_TOKEN) {
this.updateDataFromCache();
}
if (requestInfo.stateMatch) {
if (typeof callback === 'function') {
if (requestInfo.requestType === this.context.REQUEST_TYPE.RENEW_TOKEN) {
// Idtoken or Accestoken can be renewed
if (requestInfo.parameters['access_token']) {
callback(this.context._getItem(this.context.CONSTANTS.STORAGE.ERROR_DESCRIPTION)
, requestInfo.parameters['access_token']);
} else if (requestInfo.parameters['id_token']) {
callback(this.context._getItem(this.context.CONSTANTS.STORAGE.ERROR_DESCRIPTION)
, requestInfo.parameters['id_token']);
} else if (requestInfo.parameters['error']) {
callback(this.context._getItem(this.context.CONSTANTS.STORAGE.ERROR_DESCRIPTION), null);
this.context._renewFailed = true;
}
}
}
}
}
// Remove hash from url
if (removeHash) {
if (window.location.hash) {
if (window.history.replaceState) {
window.history.replaceState('', '/', window.location.pathname)
} else {
window.location.hash = '';
}
}
}
}
public getCachedToken(resource: string): string | null {
return this.context.getCachedToken(resource);
}
public acquireToken(resource: string): Observable<string | null> {
return bindCallback<string | null, string | null>((callback) => {
this.context.acquireToken(resource, (error: string, tokenOut: string) => {
if (error) {
this.context.error('Error when acquiring token for resource: ' + resource, error);
callback(null, error);
} else {
callback(tokenOut, null);
}
});
})()
.pipe<string | null>(
map((result) => {
if (!result[0] && result[1]) {
throw (result[1]);
}
return result[0];
})
);
}
public getUser(): Observable<adal.User | null> {
return bindCallback<adal.User | null>((callback) => {
this.context.getUser( (error: string, user?: adal.User) => {
if (error) {
this.context.error('Error when getting user', error);
callback(null);
} else {
callback(user || null);
}
});
})();
}
public clearCache(): void {
this.context.clearCache();
}
public clearCacheForResource(resource: string): void {
this.context.clearCacheForResource(resource);
}
public info(message: string): void {
this.context.info(message);
}
public verbose(message: string): void {
this.context.verbose(message);
}
public getResourceForEndpoint(url: string): string | null {
return this.context
? null
: this.context.getResourceForEndpoint(url);
}
public refreshDataFromCache() {
this.updateDataFromCache();
}
private updateDataFromCache(): void {
const token = this.context.getCachedToken(<any>this.context.config.loginResource);
this.user.authenticated = token !== null && token.length > 0;
const user = this.context.getCachedUser();
if (user) {
this.user.userName = user.userName;
this.user.profile = user.profile;
this.user.token = token;
this.user.error = this.context.getLoginError();
this.user.loginCached = true;
} else {
this.user.userName = '';
this.user.profile = {};
this.user.token = '';
this.user.error = this.context.getLoginError();
this.user.loginCached = false;
}
}
private refreshLoginToken(): void {
if (!this.user.loginCached) throw ("User not logged in");
this.acquireToken(<any>this.context.config.loginResource).subscribe((token: string) => {
this.user.token = token;
if (this.user.authenticated == false) {
this.user.authenticated = true;
this.user.error = '';
window.location.reload();
} else {
this.setupLoginTokenRefreshTimer();
}
}, (error: string) => {
this.user.authenticated = false;
this.user.error = this.context.getLoginError();
});
}
private now(): number {
return Math.round(new Date().getTime() / 1000.0);
}
private get isInCallbackRedirectMode(): boolean {
return window.location.href.indexOf("#access_token") !== -1 || window.location.href.indexOf("#id_token") !== -1;
};
private setupLoginTokenRefreshTimer(): void {
// Get expiration of login token
let exp = this.context._getItem(this.context.CONSTANTS.STORAGE.EXPIRATION_KEY + <any>this.context.config.loginResource);
// Either wait until the refresh window is valid or refresh in 1 second (measured in seconds)
let timerDelay = exp - this.now() - (this.context.config.expireOffsetSeconds || 300) > 0 ? exp - this.now() - (this.context.config.expireOffsetSeconds || 300) : 1;
if (this.loginRefreshTimer) this.loginRefreshTimer.unsubscribe();
this.ngZone.runOutsideAngular(() => {
this.loginRefreshTimer = timer(timerDelay * 1000).subscribe((x) => {
this.refreshLoginToken()
});
});
}
}