Question

I've just added and configured the devise gem. It's working great except for blocking my form's autosave AJAX calls.

At the top of my controller, I have:

before_filter :authenticate_user!

My AJAX call comes to the same controller:

  def autosave
    #TODO: update relative entry
    #TODO: verify user logged in
    #TODO: verify entry belongs to relative user
    render content_type: 'text/xml', inline: "<result status='ok' />"
  end

Of course I could instead declare my before filter like so:

before_filter :authenticate_user!, except: :autosave

..but this offers nothing to prevent anyone from calling this controller function at any time.

What would be the best way to allow this function to be called? I still want to ensure that only logged in users can make the call and that the given record they're editing belongs to them.

Was it helpful?

Solution

Not entirely sure what you're trying to do, but it sounds like you just need to add a bit of logic to your autosave. With this setup the function will still be called per se, but whether or not it does anything is a another mater entirely unless the conditions are right.

def autosave
  #Verify that the user is signed in and he has ownership of entry
  if !current_user.nil? && entry.user == current_user
    render content_type: 'text/xml', inline: "<result status='ok' />"
  else
    #do nothing nothing or redirect with error here
  end  
end

Since you're making an AJAX post you have to provide some additional information to your ajax call as a security countermeasure, namely a CSRF security token. See Devise not setting current_user on Ajax post even though correct x-csrf-token is included in request header for an example AJAX request using a security token. Also, make sure you also include <%= csrf_meta_tag %> in your head tag.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top