Skip to content

Instantly share code, notes, and snippets.

@ev0k3r
Forked from kkurni/TokenHandler.js
Created July 19, 2013 13:15
Show Gist options
  • Select an option

  • Save ev0k3r/6039031 to your computer and use it in GitHub Desktop.

Select an option

Save ev0k3r/6039031 to your computer and use it in GitHub Desktop.
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