Devise Ajax login: 'sessions # create' only render 'create.js.erb' when it succeeds

My goal is to implement Ajax login solution using Devise with minimal template change. I already reached it partially, but there is one problem with the failure callback. Let me explain the scenario:

  • Show the registration form in modal format using remote: trueRails / UJS convention (OK);
  • Create a user controller sessionsand specify "Specify It" (OK);
  • Create a JS view file create.js.erbto respond to the sessions#createaction (PROBLEM);

Problem: My create.js.erbcontains only alert("Test ok"). When I submit the form sessions#newwith the correct credentials, the file is executed create.js.erb, it is displayed alert. But with the wrong credentials this does not happen, returning the status 401 Unauthorizedand is create.js.erbignored.

Perhaps someone knows a quick trick to make it create.js.erbrun when the login fails. This way, I do not need to create a standalone Ajax script or modify the entire controller sessions.

Thank,

Environment:

VERSIONS:
Rails 4.0.2
Devise 3.2.2

User Session Controller:

class Website::SessionsController < ::Devise::SessionsController
  respond_to :js # without it neither on success create.js.erb runs
  layout false   # action `new` pure html which is rendered in a modal box
end

sessions / create.js.erb

alert("Test ok");

Server log in case of login failure:

Started POST "/users/sign_in" for 127.0.0.1 at 2014-03-27 09:59:47 -0300
Processing by Website::SessionsController#create as JS
  Parameters: {"utf8"=>"✓", "user"=>{"email"=>"", "password"=>"[FILTERED]"}, "commit"=>"Fazer login"}
Completed 401 Unauthorized in 1ms
+4
source share
2 answers

The problem is due to:

warden.authenticate! (...)

.

SessionController #, . , :

def create
  self.resource = warden.authenticate(auth_options)
  if resource && resource.active_for_authentication?
    ...
    sign_in(resource_name, resource)
    ...
  else
    ...
  end
end
+4

create.js.erb.

- new.js.erb.

- new.js.erb. .


, , , remote: true , create.js.erb.

//

# If http headers should be returned for AJAX requests. True by default.
config.http_authenticatable_on_xhr = false

/routes.rb

devise_for :users, controllers: { sessions: 'users/sessions' }

//sessions_controller.rb

class Users::SessionsController < Devise::SessionsController

  respond_to :html, :js

end
+5

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


All Articles