Permalink
Browse files

Add CSRF token handling to javascript emulation

  • Loading branch information...
1 parent 6d8b2be commit 6f9c53320e5be30aea6d06f7c15336ed919434af @JonathonMA JonathonMA committed Aug 24, 2011
Showing with 30 additions and 0 deletions.
  1. +30 −0 lib/cucumber/rails/capybara/javascript_emulation.rb
@@ -19,6 +19,26 @@ def click_with_javascript_emulation
private
+ def csrf?
+ csrf_param_node && csrf_token_node
+ end
+
+ def csrf_param_node
+ element_node.document.at_xpath("//meta[@name='csrf-param']")
+ end
+
+ def csrf_param
+ csrf_param_node['content']
+ end
+
+ def csrf_token_node
+ element_node.document.at_xpath("//meta[@name='csrf-token']")
+ end
+
+ def csrf_token
+ csrf_token_node['content']
+ end
+
def js_form(document, action, emulated_method, method = 'POST')
js_form = document.create_element('form')
js_form['action'] = action
@@ -31,6 +51,16 @@ def js_form(document, action, emulated_method, method = 'POST')
input['value'] = emulated_method
js_form.add_child(input)
end
+
+ # rails will wipe the session if the CSRF token is not sent
+ # with non-GET requests
+ if csrf? && emulated_method.downcase != "get"
+ input = document.create_element('input')
+ input['type'] = 'hidden'
+ input['name'] = csrf_param
+ input['value'] = csrf_token
+ js_form.add_child(input)
+ end
js_form
end

0 comments on commit 6f9c533

Please sign in to comment.