blob: 0a2bf74f76fa89a3bfa5ff557e7c3e22e9a0736b [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 Scandoloc37c5ac2017-01-09 13:43:31 -080011 if (res.status === 401 || res.status === -1) {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080012 $cookies.remove('sessionid', {path: '/'});
Matteo Scandolof1e32dc2016-12-23 17:26:39 -080013 $state.go('login');
Matteo Scandoloebe5a222017-02-27 11:09:26 -080014 return $q.reject(res);
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080015 }
16 return res;
17 };
18
19 return {
20 response: checkLogin,
21 responseError: checkLogin
22 };
23}
24
25export function CredentialsInterceptor($cookies: angular.cookies.ICookiesService) {
26 return {
27 request: (req) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080028 if (!$cookies.get('sessionid')) {
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080029 return req;
30 }
Matteo Scandolo1aee1982017-02-17 08:33:23 -080031 req.headers['x-sessionid'] = $cookies.get('sessionid');
32 req.headers['x-xossession'] = $cookies.get('sessionid');
Matteo Scandolof6acdbe2016-12-13 10:29:37 -080033 return req;
34 }
35 };
36}
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080037
38export function NoHyperlinksInterceptor() {
39 return {
40 request: (req) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080041 if (req.url.indexOf('.html') === -1) {
42 // NOTE force content type to be JSON
43 req.headers['Content-Type'] = 'application/json';
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080044 }
45 return req;
Matteo Scandolo1aee1982017-02-17 08:33:23 -080046 },
47 response: (res) => {
48 try {
49 // NOTE convert res.data from string to JSON
50 res.data = JSON.parse(res.data);
51 try {
52 // NOTE chameleon return everything inside an "items" field
53 res.data = res.data.items;
54 } catch (_e) {
55 res.data = res.data;
56 }
57 } catch (e) {
58 res.data = res.data;
59 }
60 return res;
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080061 }
62 };
63}