| 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565 |
1×
1×
1×
1×
1×
52×
52×
52×
52×
52×
52×
52×
52×
52×
52×
52×
52×
52×
16×
52×
1×
6×
1×
42×
1×
44×
44×
43×
43×
1×
86×
41×
86×
1×
43×
43×
1×
16×
16×
1×
36×
1×
11×
1×
1×
1×
5×
1×
25×
1×
1×
1×
3×
1×
2×
1×
5×
1×
4×
1×
31×
31×
31×
24×
24×
24×
22×
2×
22×
22×
2×
11×
4×
7×
4×
3×
1×
49×
3×
46×
46×
46×
1×
2×
2×
1×
1×
1×
4×
1×
47×
47×
47×
45×
1×
44×
43×
43×
43×
43×
42×
42×
1×
44×
44×
21×
23×
23×
2×
1×
1×
1×
9×
9×
1×
14×
1×
7×
3×
4×
1×
19×
19×
19×
4×
19×
1×
25×
25×
25×
1×
1×
1×
1×
1×
5×
5×
4×
4×
2×
2×
1×
12×
12×
1×
11×
11×
11×
11×
14×
10×
10×
4×
3×
4×
11×
11×
11×
10×
10×
8×
1×
42×
1×
43×
43×
42×
42×
1×
44×
44×
3×
1×
3×
3×
2×
2×
2×
2×
5×
5×
5×
5×
1×
1×
1×
1×
43×
1×
19×
1×
1×
1×
1×
1×
1×
21×
1×
20×
20×
1×
1×
1×
1×
19×
19×
19×
19×
19×
1×
2×
1×
2×
1×
2×
1×
1×
1×
1×
1×
45×
45×
45×
1×
1×
| "use strict";
var moment = require("moment");
var _ = require("lodash");
var ngJwtAuthServiceProvider_1 = require("../provider/ngJwtAuthServiceProvider");
var NgJwtAuthService = (function () {
/**
* Construct the service with dependencies injected.
* @param config
* @param $http
* @param $q
* @param $window
* @param $interval
* @param base64Service
* @param $cookies
* @param $location
*/
function NgJwtAuthService(config, $http, $q, $window, $interval, base64Service, $cookies, $location) {
var _this = this;
this.config = config;
this.$http = $http;
this.$q = $q;
this.$window = $window;
this.$interval = $interval;
this.base64Service = base64Service;
this.$cookies = $cookies;
this.$location = $location;
this.loginListeners = [];
this.logoutListeners = [];
this.loggedIn = false;
/**
* Handle token refresh timer
*/
this.tickRefreshTime = function () {
Iif (!_this.userLoggedInPromise && _this.tokenNeedsToRefreshNow()) {
_this.refreshToken();
}
};
this.userFactory = this.defaultUserFactory;
}
/**
* Get the current configuration
* @returns {INgJwtAuthServiceConfig}
*/
NgJwtAuthService.prototype.getConfig = function () {
return this.config;
};
/**
* A default implementation of the user factory if the client does not provide one
*/
NgJwtAuthService.prototype.defaultUserFactory = function (subClaim, tokenData) {
return this.$q.when(_.get(tokenData, this.config.tokenUser));
};
/**
* Service needs an init function so runtime configuration can occur before
* bootstrapping the service. This allows the user supplied LoginPromptFactory
* to be registered
*/
NgJwtAuthService.prototype.init = function () {
var _this = this;
//attempt to load the token from storage
return this.loadTokenFromStorage()
.then(function () {
_this.startRefreshTimer();
return true;
});
};
/**
* Register the refresh timer
*/
NgJwtAuthService.prototype.startRefreshTimer = function () {
//if the timer is already set, clear it so the timing is reset
if (!!this.refreshTimerPromise) {
this.cancelRefreshTimer();
}
this.refreshTimerPromise = this.$interval(this.tickRefreshTime, this.config.checkExpiryEverySeconds * 1000, null, false);
};
/**
* Cancel the refresh timer
*/
NgJwtAuthService.prototype.cancelRefreshTimer = function () {
this.$interval.cancel(this.refreshTimerPromise);
this.refreshTimerPromise = null;
};
/**
* Check if the token needs to refresh now
* @returns {boolean}
*/
NgJwtAuthService.prototype.tokenNeedsToRefreshNow = function () {
Eif (!this.rawToken) {
return false; //cant refresh if there isn't a token
}
var latestRefresh = moment(this.tokenData.data.exp * 1000).subtract(this.config.refreshBeforeSeconds, 'seconds'), nextRefreshOpportunity = moment().add(this.config.checkExpiryEverySeconds);
//needs to refresh if the the next time we could refresh is after the configured refresh before date
return (latestRefresh <= nextRefreshOpportunity);
};
/**
* Get the endpoint for login
* @returns {string}
*/
NgJwtAuthService.prototype.getLoginEndpoint = function () {
return this.config.apiEndpoints.base + this.config.apiEndpoints.login;
};
/**
* Get the endpoint for exchanging a token
* @returns {string}
*/
NgJwtAuthService.prototype.getTokenExchangeEndpoint = function () {
return this.config.apiEndpoints.base + this.config.apiEndpoints.tokenExchange;
};
/**
* Get the endpoint for getting a user's token (impersonation)
* @returns {string}
*/
NgJwtAuthService.prototype.getLoginAsUserEndpoint = function (userIdentifier) {
return this.config.apiEndpoints.base + this.config.apiEndpoints.loginAsUser + '/' + userIdentifier;
};
/**
* Get the endpoint for refreshing a token
* @returns {string}
*/
NgJwtAuthService.prototype.getRefreshEndpoint = function () {
return this.config.apiEndpoints.base + this.config.apiEndpoints.refresh;
};
/**
* Build a authentication basic header string
* @param username
* @param password
* @returns {string}
*/
NgJwtAuthService.getAuthHeader = function (username, password) {
return 'Basic ' + btoa(username + ':' + password); //note btoa is NOT supported <= IE9
};
/**
* Build a token header string
* @returns {string}
*/
NgJwtAuthService.getTokenHeader = function (token) {
return 'Token ' + token;
};
/**
* Get the standard header for a jwt token request
* @returns {string}
*/
NgJwtAuthService.prototype.getBearerHeader = function () {
if (!this.rawToken) {
throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token is not set");
}
return 'Bearer ' + this.rawToken;
};
/**
* Build a refresh header string
* @returns {string}
*/
NgJwtAuthService.prototype.getRefreshHeader = function () {
if (!this.rawToken) {
throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token is not set, it cannot be refreshed");
}
return 'Bearer ' + this.rawToken;
};
/**
* Retrieve the token from the remote API
* @param endpoint
* @param authHeader
* @returns {IPromise<IUser>}
*/
NgJwtAuthService.prototype.retrieveAndProcessToken = function (endpoint, authHeader) {
var _this = this;
var requestConfig = {
method: 'GET',
url: endpoint,
headers: {
Authorization: authHeader
},
responseType: 'json'
};
return this.$http(requestConfig).then(function (result) {
Eif (result && result.data) {
var token = _.get(result.data, _this.config.tokenLocation);
if (_.isString(token)) {
return token;
}
}
return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException("Token could not be found in response body"));
})
.then(function (token) {
try {
return _this.processNewToken(token);
}
catch (error) {
return _this.$q.reject(error);
}
})
.catch(function (e) {
if (_.isError(e) || e instanceof _this.$window.Error) {
return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException(e.message));
}
if (e.status === 401) {
return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthCredentialsFailedException("Login attempt received unauthorised response"));
}
return _this.$q.reject(new ngJwtAuthServiceProvider_1.NgJwtAuthException("The API reported an error - " + e.status + " " + e.statusText));
});
};
/**
* Parse the raw token
* @param rawToken
* @returns {IJwtToken}
*/
NgJwtAuthService.prototype.readToken = function (rawToken) {
if ((rawToken.match(/\./g) || []).length !== 2) {
throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Raw token is has incorrect format. Format must be of form \"[header].[data].[signature]\"");
}
var pieces = rawToken.split('.');
var jwt = {
header: angular.fromJson(this.base64Service.urldecode(pieces[0])),
data: angular.fromJson(this.base64Service.urldecode(pieces[1])),
signature: pieces[2],
};
return jwt;
};
/**
* Validate JWT Token
* @param rawToken
* @returns {any}
*/
NgJwtAuthService.prototype.validateToken = function (rawToken) {
try {
var tokenData = this.readToken(rawToken);
return _.isObject(tokenData);
}
catch (e) {
return false;
}
};
/**
* Prompt user for their login credentials, and attempt to login
* @returns {ng.IPromise<IUser>}
*/
NgJwtAuthService.prototype.promptLogin = function () {
return this.requireCredentialsAndAuthenticate();
};
/**
* Read and save the raw token to storage, kick off timer to attempt refresh
* @param rawToken
* @returns {IUser}
*/
NgJwtAuthService.prototype.processNewToken = function (rawToken) {
var _this = this;
this.rawToken = rawToken;
this.tokenData = this.readToken(rawToken);
if (this.tokenHasExpired()) {
throw new ngJwtAuthServiceProvider_1.NgJwtAuthTokenExpiredException("Token has expired");
}
this.saveTokenToStorage(rawToken, this.tokenData);
this.setJWTHeader(rawToken);
this.loggedIn = true;
this.startRefreshTimer();
var userFromToken = this.getUserFromTokenData(this.tokenData);
userFromToken.then(function (user) { return _this.handleLogin(user); });
return userFromToken;
};
NgJwtAuthService.prototype.loadTokenFromStorage = function () {
var rawToken = this.$window.localStorage.getItem(this.config.storageKeyName);
if (!rawToken) {
return this.$q.when("No token in storage");
}
try {
return this.processNewToken(rawToken);
}
catch (e) {
if (e instanceof ngJwtAuthServiceProvider_1.NgJwtAuthTokenExpiredException) {
return this.requireCredentialsAndAuthenticate();
}
return this.$q.reject(e);
}
};
/**
* Check if the endpoint is a login method (used for skipping the authentication error interceptor)
* @param url
* @returns {boolean}
*/
NgJwtAuthService.prototype.isLoginMethod = function (url) {
var loginMethods = [
this.getLoginEndpoint(),
this.getTokenExchangeEndpoint(),
];
return _.includes(loginMethods, url);
};
NgJwtAuthService.prototype.getUser = function () {
return this.user;
};
/**
*
* @returns {IHttpPromise<IUser>}
*/
NgJwtAuthService.prototype.getPromisedUser = function () {
if (this.loggedIn) {
return this.$q.when(this.user);
}
else {
return this.requireCredentialsAndAuthenticate();
}
};
/**
* Clear the token
*/
NgJwtAuthService.prototype.clearJWTToken = function () {
this.rawToken = null;
this.$window.localStorage.removeItem(this.config.storageKeyName);
if (this.config.cookie.enabled) {
this.$cookies.remove(this.config.cookie.name);
}
this.unsetJWTHeader();
};
/**
* Attempt to log in with username and password
* @param username
* @param password
* @returns {IPromise<boolean>}
*/
NgJwtAuthService.prototype.authenticateCredentials = function (username, password) {
var authHeader = NgJwtAuthService.getAuthHeader(username, password);
var endpoint = this.getLoginEndpoint();
return this.retrieveAndProcessToken(endpoint, authHeader);
};
/**
* Exchange an arbitrary token with a jwt token
* @param token
* @returns {ng.IPromise<any>}
*/
NgJwtAuthService.prototype.exchangeToken = function (token) {
var authHeader = NgJwtAuthService.getTokenHeader(token);
var endpoint = this.getTokenExchangeEndpoint();
return this.retrieveAndProcessToken(endpoint, authHeader);
};
/**
* Refresh an existing token
* @returns {ng.IPromise<any>}
*/
NgJwtAuthService.prototype.refreshToken = function () {
var _this = this;
var authHeader = this.getRefreshHeader();
var endpoint = this.getRefreshEndpoint();
return this.retrieveAndProcessToken(endpoint, authHeader)
.catch(function (err) {
_this.cancelRefreshTimer(); //if token refreshing fails, stop the refresh timer
return _this.$q.reject(err);
});
};
/**
* Require that the user logs in again for a request
* 1. Check if there is already credentials promised
* 2. If not, execute the credential promise factory
* 3. Wait until the credentials are resolved
* 4. Then try to authenticateCredentials
* @returns {IPromise<IUser>}
*/
NgJwtAuthService.prototype.requireCredentialsAndAuthenticate = function () {
var _this = this;
if (!_.isFunction(this.loginPromptFactory)) {
throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You must set a loginPromptFactory with `ngJwtAuthService.registerLoginPromptFactory()` so the user can be prompted for their credentials");
}
Eif (!this.userLoggedInPromise) {
var deferredCredentials_1 = this.$q.defer();
var loginSuccess_1 = this.$q.defer();
deferredCredentials_1.promise
.then(null, null, function (credentials) {
return _this.authenticateCredentials(credentials.username, credentials.password).then(function (user) {
//credentials were successful; resolve the promises
deferredCredentials_1.resolve(user);
loginSuccess_1.resolve(user);
}, function (err) {
if (!!_this.userLoggedInPromise) {
_this.userLoggedInPromise = null;
}
loginSuccess_1.notify(err);
});
});
this.userLoggedInPromise = this.loginPromptFactory(deferredCredentials_1, loginSuccess_1.promise, this.user)
.then(function () { return loginSuccess_1.promise; }, //when the user has completed the login, chain on the login success promise
function (err) {
deferredCredentials_1.reject(); //if the user aborted login, reject the credentials promise
loginSuccess_1.reject();
return _this.$q.reject(err); //and reject the login promise
});
}
return this.userLoggedInPromise
.then(function () {
return _this.getUser();
})
.finally(function () {
if (!!_this.userLoggedInPromise) {
_this.userLoggedInPromise = null;
}
});
};
/**
* Handle the login event
* @param user
*/
NgJwtAuthService.prototype.handleLogin = function (user) {
_.invokeMap(this.loginListeners, _.call, null, user);
};
/**
* Find the user object within the path
* @param tokenData
* @returns {ng.IPromise<IUser>}
*/
NgJwtAuthService.prototype.getUserFromTokenData = function (tokenData) {
var _this = this;
return this.userFactory(tokenData.data.sub, tokenData.data)
.then(function (user) {
_this.user = user;
return user;
});
};
/**
* Save the token
* @param rawToken
* @param tokenData
*/
NgJwtAuthService.prototype.saveTokenToStorage = function (rawToken, tokenData) {
this.$window.localStorage.setItem(this.config.storageKeyName, rawToken);
if (this.config.cookie.enabled) {
this.saveCookie(rawToken, tokenData);
}
};
/**
* Save to cookie
* @param rawToken
* @param tokenData
*/
NgJwtAuthService.prototype.saveCookie = function (rawToken, tokenData) {
var cookieKey = this.config.cookie.name, expires = new Date(tokenData.data.exp * 1000); //set the cookie expiry to the same as the jwt
if (this.config.cookie.topLevelDomain) {
var hostnameParts = this.$location.host().split('.');
var segmentCount = 1;
var testHostname = '';
do {
testHostname = _.takeRight(hostnameParts, segmentCount).join('.');
segmentCount++;
this.$cookies.put(cookieKey, rawToken, {
domain: testHostname,
expires: expires,
});
if (this.$cookies.get(cookieKey)) {
return; //so exit here
}
} while (segmentCount < hostnameParts.length + 1); //try all the segment combinations, exit when all attempted
throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("Could not set cookie for domain " + testHostname);
}
else {
this.$cookies.put(cookieKey, rawToken, {
expires: expires,
});
}
};
/**
* Set the authentication token for all new requests
* @param rawToken
*/
NgJwtAuthService.prototype.setJWTHeader = function (rawToken) {
this.$http.defaults.headers.common.Authorization = 'Bearer ' + rawToken;
};
/**
* Remove the default http authorization header
*/
NgJwtAuthService.prototype.unsetJWTHeader = function () {
delete this.$http.defaults.headers.common.Authorization;
};
/**
* Handle a request that was rejected due to unauthorised response
* 1. Require authentication
* 2. Retry the rejected $http request
*
* @param rejection
*/
NgJwtAuthService.prototype.handleInterceptedUnauthorisedResponse = function (rejection) {
var _this = this;
return this.requireCredentialsAndAuthenticate()
.then(function () {
//update with the new header
rejection.config.headers['Authorization'] = _this.getBearerHeader();
return _this.$http(rejection.config);
});
};
/**
* Register the login prompt factory
* @param loginPromptFactory
* @returns {NgJwtAuthService}
*/
NgJwtAuthService.prototype.registerLoginPromptFactory = function (loginPromptFactory) {
if (_.isFunction(this.loginPromptFactory)) {
throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You cannot redeclare the login prompt factory");
}
this.loginPromptFactory = loginPromptFactory;
return this;
};
/**
* Register the user factory for extracting a user from data
* @param userFactory
* @returns {NgJwtAuthService}
*/
NgJwtAuthService.prototype.registerUserFactory = function (userFactory) {
this.userFactory = userFactory;
return this;
};
/**
* Clear the token and service properties
*/
NgJwtAuthService.prototype.logout = function () {
this.clearJWTToken();
this.loggedIn = false;
//call all logout listeners with user that is logged out
_.invokeMap(this.logoutListeners, _.call, null, this.user);
this.user = null;
Iif (!!this.userLoggedInPromise) {
this.userLoggedInPromise = null;
}
};
/**
* Register a login listener function
* @param loginListener
*/
NgJwtAuthService.prototype.registerLoginListener = function (loginListener) {
this.loginListeners.push(loginListener);
};
/**
* Register a logout listener function
* @param logoutListener
*/
NgJwtAuthService.prototype.registerLogoutListener = function (logoutListener) {
this.logoutListeners.push(logoutListener);
};
/**
* Get a user's token given their identifier
* @param userIdentifier
* @returns {ng.IPromise<IUser>}
*
* Note this feature should be implemented very carefully as it is a security risk as it means users
* can log in as other users (impersonation). The responsibility is on the implementing app to strongly
* control permissions to access this endpoint to avoid security risks
*/
NgJwtAuthService.prototype.loginAsUser = function (userIdentifier) {
if (!this.loggedIn) {
throw new ngJwtAuthServiceProvider_1.NgJwtAuthException("You must be logged in to retrieve a user's token");
}
var authHeader = this.getBearerHeader();
var endpoint = this.getLoginAsUserEndpoint(userIdentifier);
return this.retrieveAndProcessToken(endpoint, authHeader);
};
/**
* @returns boolean
*/
NgJwtAuthService.prototype.tokenHasExpired = function () {
Iif (!this.rawToken) {
return false;
}
var expiryDate = moment(this.tokenData.data.exp * 1000);
return expiryDate < moment();
};
return NgJwtAuthService;
}());
exports.NgJwtAuthService = NgJwtAuthService;
|