-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccessToken.js
More file actions
73 lines (64 loc) · 2.45 KB
/
accessToken.js
File metadata and controls
73 lines (64 loc) · 2.45 KB
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
'use strict';
(function () {
var accessTokenModule = angular.module('htAccessToken', []);
accessTokenModule.factory('htAccessToken.manager', ['$window', function ($window) {
var tokenService = {
_hasToken: null,
_timeoutID: null
};
tokenService.setToken = function (accessToken, expiresIn) {
var accessTokenExpiry = Date.now() + expiresIn * 1000;
$window.localStorage.setItem('accessToken', accessToken);
$window.localStorage.setItem('accessTokenExpiry', accessTokenExpiry);
this._hasToken = true;
if (this._timeoutID !== null) {
$window.clearTimeout(this._timeoutID);
}
this._timeoutID = $window.setTimeout(function () {
tokenService.removeToken();
}, accessTokenExpiry - Date.now());
};
tokenService.getToken = function () {
return $window.localStorage.getItem('accessToken');
};
tokenService.hasToken = function () {
if (this.getToken() === null) {
return false;
}
if (this._hasToken === null) {
if ($window.localStorage.getItem('accessTokenExpiry') <= Date.now()) {
this._hasToken = false;
} else {
this._hasToken = true;
}
}
return this._hasToken;
};
tokenService.removeToken = function () {
$window.localStorage.removeItem('accessToken');
$window.localStorage.removeItem('accessTokenExpiry');
this._hasToken = false;
if (this._timeoutID !== null) {
$window.clearTimeout(this._timeoutID);
}
};
return tokenService;
}]);
/**
* Alias for htAccessToken.manager
*/
accessTokenModule.factory('htAccessTokenManager', ['htAccessToken.manager', function(htAccessTokenManager){
return htAccessTokenManager;
}]);
accessTokenModule.factory('htAccessToken.interceptor', function ($q, $window, htAccessTokenManager) {
return {
request: function (config) {
config.headers = config.headers || {};
if (htAccessTokenManager.hasToken()) {
config.headers.Authorization = 'Bearer ' + htAccessTokenManager.getToken();
}
return config;
}
};
});
})();