angular.module('admin')
.factory('tokenInterceptor', function($window, $q, $location){
  var interceptor = {};

  interceptor.response = function(response){
    var token = response.headers('X-ACCESS-TOKEN');
    if (token) {
      $window.sessionStorage.token = token;
    }
    return response;
  };

  interceptor.request = function(config){
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers['Authorization'] = 'Bearer ' + $window.sessionStorage.token;
      }
      return config;
    };

    interceptor.responseError = function(rejection){
      if (rejection != null && rejection.status == 401) {
        delete $window.sessionStorage.token;
        $location.path('/');
      }
      return $q.reject(rejection);
    };

    return interceptor;
});
