问题描述:

I want manage privates views and functions of my website.

I use an interceptor factory for each request :

var APIInterceptor = {

request: function(config) {

if ($cookies.get('access_token')) config.headers['Authorization'] = 'Basic ' + $cookies.get('access_token');

return config || $q.when(config);

},

requestError: function(rejection) {

return $q.reject(rejection);

},

response: function(response) {

// Return the response or promise.

return response || $q.when(response);

},

responseError: function(rejection) {

if (rejection.status === 401) {

var Session = $injector.get('Session');

Session.destroy(rejection.data.message);

} else if (rejection.status === 403) {

}

return $q.reject(rejection);

}

I configure my routes in .config() like this :

angular

.module('app.routes', ['ngRoute'])

.config(config);

function config($httpProvider, $routeProvider, $locationProvider) {

// Reset headers to avoid OPTIONS request (aka preflight)

$httpProvider.defaults.headers.common = {};

$httpProvider.defaults.headers.post = {};

$httpProvider.defaults.headers.put = {};

$httpProvider.defaults.headers.patch = {};

// Interceptors

$httpProvider.interceptors.push('APIInterceptor');

$routeProvider

.when("/auth",

{

templateUrl: "partials/auth/auth.tpl.html",

controller: 'AuthController'

})

.when("/",

{

templateUrl: "partials/home/home.tpl.html",

controller: 'HomeController'

})

.otherwise({ redirectTo: "/" });

}

I destroy the session when the response status is 401 in the .run() :

angular.module('app.config', [])

.run(start);

function start($rootScope, Session, LOCAL) {

$rootScope.config = LOCAL;

$rootScope.$on('session:destroy', function (event, args) {

console.log('Destruction de la session');

$location.url('/');

});

};

This is a great way when the response return a 401 and 403 status. But How it's possible to use interceptor for routing ?

Because when the route changes, the status code is always 200, even if the token doesn't exist.

Should I set manually the status code to 401 or 403 in response when $cookie, or $localStorage token doesn't exist or I must achieve this with other method, maybe with the $onRouteChange method ? I haven't find anything thereupon.

相关阅读:
Top