1/**
2 * api Interceptor
3 *
4 * @module app/common/services/apiInterceptor
5 * @exports apiInterceptor
6 * @name apiInterceptor
7
8 */
9
10window.angular && (function(angular) {
11  'use strict';
12
13  angular.module('app.common.services').service('apiInterceptor', [
14    '$q', '$rootScope', 'dataService', '$location',
15    function($q, $rootScope, dataService, $location) {
16      return {
17        'request': function(config) {
18          dataService.loading = true;
19          // If caller has not defined a timeout, set to default of 20s
20          if (config.timeout == null) {
21            config.timeout = 20000;
22          }
23          return config;
24        },
25        'response': function(response) {
26          dataService.loading = false;
27
28          // not interested in template requests
29          if (!/^https?\:/i.test(response.config.url)) {
30            return response;
31          }
32
33          dataService.last_updated = new Date();
34          if (!response) {
35            dataService.server_unreachable = true;
36          } else {
37            dataService.server_unreachable = false;
38          }
39
40          if (response && response.status == 'error' &&
41              dataService.path != '/login') {
42            $rootScope.$emit('timedout-user', {});
43          }
44
45          return response;
46        },
47        'responseError': function(rejection) {
48          if (dataService.ignoreHttpError === false) {
49            // If unauthorized, log out
50            if (rejection.status == 401) {
51              if (dataService.path != '/login') {
52                $rootScope.$emit('timedout-user', {});
53              }
54            } else if (rejection.status == 403) {
55              // TODO: when permission role mapping ready, remove
56              // this global redirect and handle forbidden
57              // requests in context of user action
58              if (dataService.path != '/login') {
59                $location.url('/unauthorized');
60              }
61            } else if (rejection.status == -1) {
62              dataService.server_unreachable = true;
63            }
64
65            dataService.loading = false;
66          }
67          return $q.reject(rejection);
68        }
69      };
70    }
71  ]);
72})(window.angular);
73