Skip to content

Instantly share code, notes, and snippets.

@PoTHuYJoHN
Created June 7, 2017 10:46
Show Gist options
  • Save PoTHuYJoHN/bfcf7106a90a3c0e2a5a3ee6ced7ad23 to your computer and use it in GitHub Desktop.
Save PoTHuYJoHN/bfcf7106a90a3c0e2a5a3ee6ced7ad23 to your computer and use it in GitHub Desktop.
function authInterceptor($rootScope, localStorageService, $q, $timeout, $location, APP_CONFIG) {
return {
response : function(response) {
if(response) {
var freshJwt = response.headers().authorization;
if (freshJwt) {
//refresh local token
localStorageService.set(APP_CONFIG.jwt_key, freshJwt);
}
if (typeof response.data === 'object') {
// Redirect to page, if user was not authorized.
if (response.data.authorization === false) {
$rootScope.auth = {};
localStorageService.remove(APP_CONFIG.jwt_key);
localStorageService.remove('satellizer_token');
$timeout(function () {
$location.path('/logout');
});
}
}
}
return response;
},
// Intercept 401s and redirect you to login
responseError: function(response) {
if(response.status === 401) {
// remove any stale tokens
$rootScope.auth = {};
localStorageService.remove(APP_CONFIG.jwt_key);
localStorageService.remove('satellizer_token');
$timeout(function () {
$location.path('/logout');
});
return $q.reject(response);
} else {
var freshJwt = response.headers().authorization;
if (freshJwt) {
//refresh local token
localStorageService.set(APP_CONFIG.jwt_key, freshJwt);
}
return $q.reject(response);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment