-
-
Save timelf123/15a059cea824eac39002c9600d1c9a21 to your computer and use it in GitHub Desktop.
Set specific http headers on every http request from cookies (angular)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/** | |
* Authentication with token and email for every server request. (Sets HTTP headers) | |
* | |
* This interceptor shows the error from the server (i18n key). | |
* Also sets global error variable if the request fails and redirects the user to '/' when he is not authorized. | |
* @see http://engineering.talis.com/articles/client-side-error-logging/ | |
*/ | |
app.factory('authInterceptor', function ($rootScope, $q, $cookies, $location, $timeout) { | |
return { | |
request: function (config) { | |
delete $rootScope.errorKey; | |
config.headers = config.headers || {}; | |
if ($cookies.authenticationToken && $cookies.email) { | |
config.headers['X-AUTH-TOKEN'] = $cookies.authenticationToken; | |
config.headers['X-AUTH-EMAIL'] = $cookies.email; | |
} | |
return config; | |
}, | |
responseError: function (response) { | |
var status = response.status; | |
// user is not authenticated -> redirect | |
if(status === 401) { | |
$rootScope.errorKey = 'global.errors.unauthorized'; | |
$timeout(function () { | |
$location.path('/'); | |
}, 3000); | |
// ignore form validation errors because there are handled in the specific controller | |
} else if(status !== 0 && angular.isUndefined(response.data.errors)) { | |
// server error | |
if(response.data.text) { | |
$rootScope.errorKey = response.data.text; | |
} else { | |
$rootScope.showErrorMsg = true; // general error message | |
$timeout(function() { | |
$rootScope.showErrorMsg = false; | |
}, 5000); | |
} | |
} | |
return $q.reject(response); | |
} | |
}; | |
}); | |
app.config(function($httpProvider) { | |
$httpProvider.interceptors.push('authInterceptor'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment