blob: a79765e7992a780ed606a696e7a9d2533ef9891c [file] [log] [blame]
Matteo Scandolof6acdbe2016-12-13 10:29:37 -08001/// <reference path="../typings/index.d.ts" />
2
Matteo Scandolof6acdbe2016-12-13 10:29:37 -08003export function interceptorConfig($httpProvider: angular.IHttpProvider, $resourceProvider: angular.resource.IResourceServiceProvider) {
4 $httpProvider.interceptors.push('UserStatusInterceptor');
5 $httpProvider.interceptors.push('CredentialsInterceptor');
Matteo Scandolof2c3ed62016-12-15 14:32:50 -08006 $httpProvider.interceptors.push('NoHyperlinksInterceptor');
Matteo Scandolof6acdbe2016-12-13 10:29:37 -08007}
8
Matteo Scandoloebe5a222017-02-27 11:09:26 -08009export function userStatusInterceptor($state: angular.ui.IStateService, $cookies: ng.cookies.ICookiesService, $q: ng.IQService) {
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080010 const checkLogin = (res) => {
Matteo Scandolo042ea632017-03-01 19:02:34 -080011 switch (res.status) {
12 case -1:
13 case 401:
14 case 500:
15 $cookies.remove('sessionid', {path: '/'});
16 $state.go('login');
17 return $q.reject(res);
18 default:
19 return res;
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080020 }
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080021 };
22
23 return {
24 response: checkLogin,
25 responseError: checkLogin
26 };
27}
28
29export function CredentialsInterceptor($cookies: angular.cookies.ICookiesService) {
30 return {
31 request: (req) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080032 if (!$cookies.get('sessionid')) {
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080033 return req;
34 }
Matteo Scandolo1aee1982017-02-17 08:33:23 -080035 req.headers['x-sessionid'] = $cookies.get('sessionid');
36 req.headers['x-xossession'] = $cookies.get('sessionid');
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080037 return req;
38 }
39 };
40}
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080041
42export function NoHyperlinksInterceptor() {
43 return {
44 request: (req) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080045 if (req.url.indexOf('.html') === -1) {
46 // NOTE force content type to be JSON
47 req.headers['Content-Type'] = 'application/json';
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080048 }
49 return req;
Matteo Scandolo1aee1982017-02-17 08:33:23 -080050 },
51 response: (res) => {
52 try {
53 // NOTE convert res.data from string to JSON
54 res.data = JSON.parse(res.data);
55 try {
56 // NOTE chameleon return everything inside an "items" field
57 res.data = res.data.items;
58 } catch (_e) {
59 res.data = res.data;
60 }
61 } catch (e) {
62 res.data = res.data;
63 }
64 return res;
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080065 }
66 };
67}