Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle devise's authenticate_user! with ajax call?

I have a form with :remote => true which means it will be submitted through ajax.

In the controller, I have such code:

before_filter: authenticate_user!, :only => [:create]

For I only allow confirmed user to create resource.

However, when the authentication fails, devise will raise a

Completed 401 Unauthorized

and no unobtrusive javascript will be rendered.

But I hope things goes like this:

devise set some messages in flash, and render my .js.erb, then I show the flash to users.

How to achieve it?

like image 456
HanXu Avatar asked Mar 28 '12 05:03

HanXu


2 Answers

It is quite funny but change in devise.rb http_authenticatable_on_xhr to false

config.http_authenticatable_on_xhr = false

did the trick for me... without overriding authenticate_user! method

note: I also added :js to navigational formats

config.navigational_formats = [:"*/*", "*/*", :html, :js]
like image 142
Piotr Mąsior Avatar answered Oct 29 '22 23:10

Piotr Mąsior


You need do your own authenticate_user! action and in this action you can have the behaviour your want.

def authenticate_user!
  unless current_user
    render 'my_js'
  end
end
like image 45
shingara Avatar answered Oct 29 '22 23:10

shingara