Skip to content

Instantly share code, notes, and snippets.

@kkurni
Last active December 11, 2015 21:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kkurni/4662548 to your computer and use it in GitHub Desktop.
Save kkurni/4662548 to your computer and use it in GitHub Desktop.
Angular JS Factory for Token Handler which inject authorization header request. This must use in combination with my custom resource which modified based on 1.1.2 - https://gist.github.com/4662478
KK.factory('TokenHandler', ['$cookieStore', function ($cookieStore) {
var tokenHandler = {};
tokenHandler.setToken = function (newToken) {
$cookieStore.put("X-Authorization-Token", newToken);
console.log('set token ' + newToken);
};
tokenHandler.getToken = function () {
console.log('get cookie ' + $cookieStore.get("X-Authorization-Token"));
return $cookieStore.get("X-Authorization-Token");
};
// wraps given actions of a resource to send auth token
// with every request
tokenHandler.wrapActions = function (resource, actions) {
// copy original resource
var wrappedResource = resource;
// loop through actions and actually wrap them
for (var i = 0; i < actions.length; i++) {
tokenWrapper(wrappedResource, actions[i]);
};
// return modified copy of resource
return wrappedResource;
};
// wraps resource action to send request with auth token
var tokenWrapper = function (resource, action) {
// copy original action
resource['_' + action] = resource[action];
// create new action wrapping the original
// and sending token
resource[action] = function (param, data, success, error) {
var interceptSuccess = function(responseData, headers) {
var token = headers('x-token');
if (token) {
//update token
tokenHandler.setToken(token);
}
if (angular.isFunction(success)) {
success(responseData, headers);
}
};
return resource['_' + action](
angular.extend({}, param || {}, { 'Token': tokenHandler.getToken() }),
data,
interceptSuccess,
error
);
};
};
return tokenHandler;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment