all files / app/components/authInterceptor/ authHttpInterceptor.service.js

100% Statements 16/16
100% Branches 2/2
100% Functions 5/5
100% Lines 16/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                            479×   479× 479×                       17×   17×     479×                           210× 210×              
/**
 * @ngdoc service
 * @name app.components.authHttpInterceptor
 * @description
 * Intercepts HTTP error 401 unauthorized and notifies subscribers.  This
 * error means that the auth token is no longer valid.
 *
 */
(function () {
  'use strict';
 
  angular
    .module('app.components')
    .service('authHttpInterceptor', service);
 
  /** @ngInject */
  function service($q, $rootScope) {
    var service = this;
 
    service.responseError = responseError;
    service.subscribeUnauthorized = subscribeUnauthorized;
 
    /**
     * @ngdoc function
     * @name responseError
     * @methodOf app.components.authHttpInterceptor
     * @description
     * Intercepts HTTP responses
     *
     * @param {Object} response
     * HTTP response
     */
    function responseError(response) {
      if (response.status == 401) {
        emitUnauthorized();
      }
      return $q.reject(response);
    }
 
    var EVENT_NAME = 'auth-interceptor:unauthorized';
 
    /**
     * @ngdoc function
     * @name subscribeUnauthorized
     * @methodOf app.components.authHttpInterceptor
     * @description
     * Register to receive a notification when an HTTP 401 error occurs
     *
     * @param {Object} scope
     * Controller scope
     * @param {Function} callback
     * Function to call when HTTP 401 occurs
     */
    function subscribeUnauthorized(scope, callback) {
      var handler = $rootScope.$on(EVENT_NAME, callback);
      scope.$on('$destroy', handler);
    }
 
    function emitUnauthorized() {
      $rootScope.$emit(EVENT_NAME);
    }
  }
 
})();