Skip to content

Commit f8d4be4

Browse files
committed
Merge pull request #350 from derekprior/dp-refresh-csrf
Expose CSRF Token refresh as a function
2 parents 7eaaf28 + c7dcc34 commit f8d4be4

File tree

3 files changed

+33
-5
lines changed

3 files changed

+33
-5
lines changed

src/rails.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,13 @@
5757
if (token) xhr.setRequestHeader('X-CSRF-Token', token);
5858
},
5959

60+
// making sure that all forms have actual up-to-date token(cached forms contain old one)
61+
refreshCSRFTokens: function(){
62+
var csrfToken = $('meta[name=csrf-token]').attr('content');
63+
var csrfParam = $('meta[name=csrf-param]').attr('content');
64+
$('form input[name="' + csrfParam + '"]').val(csrfToken);
65+
},
66+
6067
// Triggers an event on an element and returns false if the event result is false
6168
fire: function(obj, name, data) {
6269
var event = $.Event(name);
@@ -384,10 +391,7 @@
384391
});
385392

386393
$(function(){
387-
// making sure that all forms have actual up-to-date token(cached forms contain old one)
388-
var csrfToken = $('meta[name=csrf-token]').attr('content');
389-
var csrfParam = $('meta[name=csrf-param]').attr('content');
390-
$('form input[name="' + csrfParam + '"]').val(csrfToken);
394+
rails.refreshCSRFTokens();
391395
});
392396
}
393397

test/public/test/csrf-refresh.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
(function(){
2+
3+
module('csrf-refresh', {});
4+
5+
asyncTest('refresh all csrf tokens', 1, function() {
6+
var correctToken = "cf50faa3fe97702ca1ae";
7+
8+
var form = $('<form />')
9+
var input = $('<input>').attr({ type: 'hidden', name: 'authenticity_token', id: 'authenticity_token', value: 'foo' })
10+
input.appendTo(form)
11+
12+
$('#qunit-fixture')
13+
.append('<meta name="csrf-param" content="authenticity_token"/>')
14+
.append('<meta name="csrf-token" content="' + correctToken + '"/>')
15+
.append(form);
16+
17+
$.rails.refreshCSRFTokens();
18+
currentToken = $('#qunit-fixture #authenticity_token').val();
19+
20+
start();
21+
equal(currentToken, correctToken);
22+
});
23+
24+
})();

test/views/index.erb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<% @title = "jquery-ujs test" %>
22

3-
<%= test 'data-confirm', 'data-remote', 'data-disable', 'call-remote', 'call-remote-callbacks', 'data-method', 'override' %>
3+
<%= test 'data-confirm', 'data-remote', 'data-disable', 'call-remote', 'call-remote-callbacks', 'data-method', 'override', 'csrf-refresh' %>
44

55
<h1 id="qunit-header"><%= @title %></h1>
66
<div id="jquery-cdn">

0 commit comments

Comments
 (0)