Forked from nblumoe/angularjs_resource_tokenhandler.js
Last active
September 3, 2015 22:58
-
-
Save alexpchin/e68d20f266ce0a1f27b4 to your computer and use it in GitHub Desktop.
AngularJS service to send auth token with $resource requests
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
.factory('TokenHandler', function() { | |
var tokenHandler = {}; | |
var token = "none"; | |
tokenHandler.set = function( newToken ) { | |
token = newToken; | |
}; | |
tokenHandler.get = function() { | |
return token; | |
}; | |
// wrap given actions of a resource to send auth token with every | |
// request | |
tokenHandler.wrapActions = function( resource, actions ) { | |
// copy original resource | |
var wrappedResource = resource; | |
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( data, success, error){ | |
return resource['_' + action]( | |
angular.extend({}, data || {}, {access_token: tokenHandler.get()}), | |
success, | |
error | |
); | |
}; | |
}; | |
return tokenHandler; | |
}); | |
----------------------- | |
Use: | |
------------------------- | |
var resource = $resource('http://localhost:port/todos/:id', { | |
port:":3001", | |
id:'@id' | |
}, { | |
update: {method: 'PUT'} | |
}); | |
resource = tokenHandler.wrapActions( resource, | |
["query", "update", "save"] ); | |
return resource; | |
}]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment