Created
August 31, 2013 03:21
-
-
Save alchemycs/6396034 to your computer and use it in GitHub Desktop.
Example Angular http service interceptor (from http://www.twilio.com/blog/2013/08/votr-part-4-angularjs-and-authentication-with-couchdb.html)
This file contains 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
app.config(function($httpProvider) { | |
$httpProvider.interceptors.push(function($rootScope, $location, $q) { | |
return { | |
'request': function(request) { | |
// if we're not logged-in to the AngularJS app, redirect to login page | |
$rootScope.loggedIn = $rootScope.loggedIn || $rootScope.username; | |
if (!$rootScope.loggedIn && $location.path() != '/login') { | |
$location.path('/login'); | |
} | |
return request; | |
}, | |
'responseError': function(rejection) { | |
// if we're not logged-in to the web service, redirect to login page | |
if (rejection.status === 401 && $location.path() != '/login') { | |
$rootScope.loggedIn = false; | |
$location.path('/login'); | |
} | |
return $q.reject(rejection); | |
} | |
}; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment