Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save krishnamurthypradeep/ac34f26dee8385ea220f to your computer and use it in GitHub Desktop.
Save krishnamurthypradeep/ac34f26dee8385ea220f to your computer and use it in GitHub Desktop.

Revisions

  1. @nblumoe nblumoe created this gist Jul 5, 2012.
    40 changes: 40 additions & 0 deletions angularjs_resource_tokenhandler.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    .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;
    });