backbone-csrf-rails
Version:
JavaScript's functional programming helper library.
24 lines (20 loc) • 868 B
JavaScript
// From http://ngauthier.com/2011/02/backbone-and-rails-forgery-protection.html
var Backbone = require('backbone');
/* alias away the sync method */
Backbone._sync = Backbone.sync;
var $ = Backbone.$;
/* define a new sync method */
Backbone.sync = function(method, model, success, error) {
/* only need a token for non-get requests */
if (method == 'create' || method == 'update' || method == 'delete') {
/* grab the token from the meta tag rails embeds */
var auth_options = {};
auth_options[$("meta[name='csrf-param']").attr('content')] =
$("meta[name='csrf-token']").attr('content');
/* set it as a model attribute without triggering events */
model.set(auth_options, {silent: true});
}
/* proxy the call to the old sync method */
return Backbone._sync(method, model, success, error);
};
module.exports = Backbone;