Authentication signature is created differently when using render_to_string

I generate a small form via render_to_string , and for some reason the CSRF token is not generated correctly (i.e. it is different from the header, and the user logs out of the submit, as well as "Unable to validate CSRF token" in the logs). Here is the relevant code:

Controller:

 def publish @question = @event.questions.find(params[:id]) @question.update_attribute(:published, true) unless @question.published? Pusher[@event.to_param].trigger('new_question', question: render_question) redirect_to event_path(@event) end private def render_question render_to_string('questions/_unanswered_question', locals: {question: @question}, layout: false) end def fetch_event @event ||= current_user.events.find(params[:event_id]) end 

I use Pusher, but you can assume that it just displays on the page using this Javascript:

 $("#questions").append(data.question); // data is what I send from Pusher. 

And finally, a partial display:

 .answer = form_for [@event, question, question.answers.new] do |f| %h2 = question.title %ul - (1..5).each do |n| - if question.send("answer_#{n}").present? %li = f.radio_button :option, n, id: "q_#{question.id}_answer_option_#{n}" = f.label question.send("answer_#{n}"), for: "q_#{question.id}_answer_option_#{n}" %p = f.submit "Answer" 

This works fine, but not added to the page, but displayed in the layout. Please note that this is not a remote form.

+4
source share
1 answer

It looks like you are generating a form using ajax and then adding it to Dom. The csrf token is generated new for each request. As far as I know, you need to use the csrf token, which is available in the header, and replace it in the form with js.

It should look something like this:

 success: ()-> parameter = $("meta[name=csrf-param]").attr("content") token = $("meta[name=csrf-token]").attr("content") question = $(data.question).find("[name="+parameter+"]").val(token) 

I currently do not have a computer to check this out first, so hopefully I'm right: /

0
source

Source: https://habr.com/ru/post/1494348/


All Articles