Hi,
I've been working to get Devise to authenticate via an AJAX request
but am having no luck. I'm using Rails 3.0.9, Ruby 1.9.2, Devise 1.4.2/
Warden 1.0.5. Here is my current setup:
# config/initializers/devise.rb
config.http_authenticatable_on_xhr = false
config.navigational_formats = [:html, :js]
# config/routes.rb
devise_for :users do
post "/login" => "sessions#create", :as => :login
end
# a variation on
https://gist.github.com/418243 to get the failure
recall to work
# app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
def create
resource = warden.authenticate!(:scope => resource_name, :recall
=> "#{controller_path}#failure")
sign_in_and_redirect(resource_name, resource)
end
def sign_in_and_redirect(resource_or_scope, resource=nil)
scope = Devise::Mapping.find_scope!(resource_or_scope)
resource ||= resource_or_scope
sign_in(scope, resource)
render :json => { :success => true, :redirect =>
stored_location_for(scope) || after_sign_in_path_for(resource) }
end
def failure
render :json => {:success => false, :errors => {:reason => "Login
failed. Try again"}}
end
end
# my view
<%= form_tag(login_path, :method => "POST", :remote => true) do%>
<%= hidden_field_tag "user[remember_me]", 1 %>
<%= label_tag "user[username]", "Username" %>
<%= text_field_tag "user[username]" %>
<%= label_tag "user[password]", "Password" %>
<%= text_field_tag "user[password]", nil, :type => "password" %>
<%= submit_tag "Sign in", :name => "commit" %>
<% end %>
The AJAX request sends out correctly from the view, and has the exact
same parameters as the off the shelf devise/sessions#new view form has
- the only difference I can see is that the POST occurs via AJAX. I
traced down into the warden code and it appears that no
winning_strategy is ever given to the AJAX request, and the user is
never authenticated. I've combed over the previous threads on this
group [1] [2] and tried their solutions and methods to no avail.
Any help is greatly appreciated, and I'd be happy to write up a wiki
page for the advised setup on the github project when I have this
working.
Thank you!
--
Chris Roby
[1]
http://groups.google.com/group/plataformatec-devise/browse_thread/thread/ce393609f40c15d8
[2]
http://groups.google.com/group/plataformatec-devise/browse_thread/thread/30553801dc60076a