Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Expose CSRF Token refresh as a function

Refreshing CSRF tokens ensures that forms do not contain cached tokens.
This is currently done once, when jquery-ujs is loaded. If a cached form
is later loaded onto the page (say via a remote form for 'load more'),
the CSRF token is not udated.

This change exposes the CSRF token refreshing code at
`$.rails.refreshCSRFTokens` so it can be called at will without developers
having to re-implement the function.
  • Loading branch information...
commit c7dcc344eefcd9a646fe570f00fec73078ecb6c4 1 parent 7eaaf28
@derekprior derekprior authored
View
12 src/rails.js
@@ -57,6 +57,13 @@
if (token) xhr.setRequestHeader('X-CSRF-Token', token);
},
+ // making sure that all forms have actual up-to-date token(cached forms contain old one)
+ refreshCSRFTokens: function(){
+ var csrfToken = $('meta[name=csrf-token]').attr('content');
+ var csrfParam = $('meta[name=csrf-param]').attr('content');
+ $('form input[name="' + csrfParam + '"]').val(csrfToken);
+ },
+
// Triggers an event on an element and returns false if the event result is false
fire: function(obj, name, data) {
var event = $.Event(name);
@@ -384,10 +391,7 @@
});
$(function(){
- // making sure that all forms have actual up-to-date token(cached forms contain old one)
- var csrfToken = $('meta[name=csrf-token]').attr('content');
- var csrfParam = $('meta[name=csrf-param]').attr('content');
- $('form input[name="' + csrfParam + '"]').val(csrfToken);
+ rails.refreshCSRFTokens();
});
}
View
24 test/public/test/csrf-refresh.js
@@ -0,0 +1,24 @@
+(function(){
+
+module('csrf-refresh', {});
+
+asyncTest('refresh all csrf tokens', 1, function() {
+ var correctToken = "cf50faa3fe97702ca1ae";
+
+ var form = $('<form />')
+ var input = $('<input>').attr({ type: 'hidden', name: 'authenticity_token', id: 'authenticity_token', value: 'foo' })
+ input.appendTo(form)
+
+ $('#qunit-fixture')
+ .append('<meta name="csrf-param" content="authenticity_token"/>')
+ .append('<meta name="csrf-token" content="' + correctToken + '"/>')
+ .append(form);
+
+ $.rails.refreshCSRFTokens();
+ currentToken = $('#qunit-fixture #authenticity_token').val();
+
+ start();
+ equal(currentToken, correctToken);
+});
+
+})();
View
2  test/views/index.erb
@@ -1,6 +1,6 @@
<% @title = "jquery-ujs test" %>
-<%= test 'data-confirm', 'data-remote', 'data-disable', 'call-remote', 'call-remote-callbacks', 'data-method', 'override' %>
+<%= test 'data-confirm', 'data-remote', 'data-disable', 'call-remote', 'call-remote-callbacks', 'data-method', 'override', 'csrf-refresh' %>
<h1 id="qunit-header"><%= @title %></h1>
<div id="jquery-cdn">

1 comment on commit c7dcc34

@amolpujari

simply great, I just had happened to re-implement the same.

Please sign in to comment.
Something went wrong with that request. Please try again.