Last active
March 21, 2017 02:23
-
-
Save martianyi/864044e8148b882717e7 to your computer and use it in GitHub Desktop.
angularjs security interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var securityInterceptor = angular.module('security.interceptor', []); | |
//securityInterceptor, add token to page_header | |
securityInterceptor.factory('securityInterceptor', ['$q', '$cookieStore', '$location', 'toaster', | |
function ($q, $cookieStore, $location, toaster) { | |
var token = $cookieStore.get('token'); | |
return { | |
'request': function (config) { | |
config.headers = config.headers || {}; | |
if (token) { | |
config.headers.Authorization = 'Token ' + token; | |
} | |
return config; | |
}, | |
'responseError': function (rejection) { | |
if (rejection.status === 401) { | |
$location.path('/login'); | |
} | |
else if (rejection.status === 403) { | |
toaster.pop('error', '', 'Unauthorized'); | |
$location.path('/login').replace(); | |
} | |
return $q.reject(rejection); | |
} | |
}; | |
}]); | |
//add the securityInterceptor to http config | |
securityInterceptor.config(['$httpProvider', function ($httpProvider) { | |
$httpProvider.interceptors.push('securityInterceptor'); | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment