4

2 places in my Rails app have ajax calls. (one for jQueryUI drag-and-drop sorting, and one for updating a comment post).

Whenever these calls occur, the user gets logged out. For no apparent reason. I'm using omniauth-facebook and omniauth-google-oauth2 for authentication.

How can this get fixed?

Here's what the ajax call looks like (coffeescript):

  $.ajax({
    type: 'put',
    data: {post_id: post.attr("id")},
    dataType: 'json',
    complete: -> post.children('.headpost').children('.buttons').removeClass('new_reply'),
    url: '/posts/update/'})

Thanks!

Arcolye
  • 6,968
  • 4
  • 34
  • 28
  • http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails/ Okay, the session gets reset because my ajax request doesn't have the authenticity token. Now, how to do that with an ajax request in an assets coffeescript file... – Arcolye Mar 14 '12 at 04:28

1 Answers1

3

What I ended up doing:

In application.html.erb layout head, under <%= csrf_meta_tags %>:

<%= javascript_tag "var AUTH_TOKEN = '#{form_authenticity_token}';" if protect_against_forgery?%>

In assets/whatever.js.coffee

$.ajax ({
            type: 'put',
            data: {authenticity_token: AUTH_TOKEN},
            dataType: 'json',
            complete: -> post.children('.headpost').children('.buttons').removeClass('new_reply'),
            url: '/posts/'+post.attr("id").slice(5) });
Arcolye
  • 6,968
  • 4
  • 34
  • 28
  • thanks to http://stackoverflow.com/questions/7560837/proper-way-to-send-an-authenticity-token-with-ajax – Arcolye Mar 14 '12 at 04:55