token refresh

This commit is contained in:
Kyle Spearrin 2017-01-28 16:09:38 -05:00
parent a20e8b6228
commit e674e7287e
3 changed files with 42 additions and 18 deletions

View File

@ -2,38 +2,44 @@ angular
.module('bit')
.config(function ($stateProvider, $urlRouterProvider, $httpProvider, jwtInterceptorProvider, $uibTooltipProvider, toastrConfig) {
var refreshingToken = null;
jwtInterceptorProvider.urlParam = 'access_token2';
jwtInterceptorProvider.tokenGetter = /*@ngInject*/ function (config, appSettings, tokenService, apiService, jwtHelper) {
var refreshPromise;
jwtInterceptorProvider.tokenGetter = /*@ngInject*/ function (config, appSettings, tokenService, apiService, jwtHelper, $q) {
if (config.url.indexOf(appSettings.apiUri) !== 0) {
return;
}
if (refreshPromise) {
return refreshPromise;
}
var token = tokenService.getToken();
var refreshToken = tokenService.getRefreshToken();
if (!token) {
return;
}
if (!jwtHelper.isTokenExpired(tokenService.getToken())) {
if (!tokenService.tokenNeedsRefresh(token)) {
return token;
}
if (refreshingToken === null) {
refreshingToken = apiService.identity.token({
var refreshToken = tokenService.getRefreshToken();
if (!refreshToken) {
return;
}
var deferred = $q.defer();
apiService.identity.token({
grant_type: 'refresh_token',
client_id: 'web',
refresh_token: refreshToken
}, function (response) {
tokenService.setToken(response.access_token);
tokenService.setRefreshToken(response.refresh_token);
refreshingToken = null;
}, function () {
refreshingToken = null;
refreshPromise = null;
deferred.resolve(response.access_token);
});
}
return refreshingToken;
refreshPromise = deferred.promise;
return refreshPromise;
};
angular.extend(toastrConfig, {

View File

@ -63,6 +63,7 @@
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
transformRequest: transformUrlEncoded,
skipAuthorization: true,
params: {}
}
});

View File

@ -1,7 +1,7 @@
angular
.module('bit.services')
.factory('tokenService', function ($sessionStorage) {
.factory('tokenService', function ($sessionStorage, jwtHelper) {
var _service = {},
_token = null,
_refreshToken = null;
@ -42,5 +42,22 @@ angular
delete $sessionStorage.refreshToken;
};
_service.tokenSecondsRemaining = function (token, offsetSeconds) {
var d = jwtHelper.getTokenExpirationDate(token);
offsetSeconds = offsetSeconds || 0;
if (d === null) {
return 0;
}
var msRemaining = d.valueOf() - (new Date().valueOf() + (offsetSeconds * 1000));
return Math.round(msRemaining / 1000);
};
_service.tokenNeedsRefresh = function (token, minutes) {
minutes = minutes || 5; // default 5 minutes
var sRemaining = _service.tokenSecondsRemaining(token);
return sRemaining < (60 * minutes);
};
return _service;
});