Devise - Login with Ajax

Is there any way to change the construction of a SessionController for ajax communication?

Edit

I found a solution and sent it back, thanks

+4
source share
1 answer

1. Generate Devise Controllers So We Can Change It

rails g devise:controllers

enter image description here

Now we have all the controllers in the application / controller directory / [model]

2. Edit route.rb

Let set Devise use our modified SessionController

First add this code (of course change: users to your development model) in config / routes.rb

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

3. Change session_controller.rb

enter image description here

Find a way to create it and change it to

def create
  resource = User.find_for_database_authentication(email: params[:user][:email])
  return invalid_login_attempt unless resource

  if resource.valid_password?(params[:user][:password])
    sign_in :user, resource
    return render nothing: true
  end

  invalid_login_attempt
 end

def invalid_login_attempt
  set_flash_message(:alert, :invalid)
  render json: flash[:alert], status: 401
end

4. devise.rb

config/initializers/devise.rb

config.http_authenticatable_on_xhr = false
config.navigational_formats = ["*/*", :html, :json]

5.

config/locales/devise.en.yml

invalid: "Invalid email or password."

sessions

6.

= form_for resource, url: session_path(:user), remote: true do |f|
  = f.text_field :email
  = f.password_field :password
  = f.label :remember_me do
    Remember me
    = f.check_box :remember_me
  = f.submit value: 'Sign in'

:javascript
  $(document).ready(function() {
    //form id
    $('#new_user')
    .bind('ajax:success', function(evt, data, status, xhr) {
      //function called on status: 200 (for ex.)
      console.log('success');
    })
    .bind("ajax:error", function(evt, xhr, status, error) {
      //function called on status: 401 or 500 (for ex.)
      console.log(xhr.responseText);
    });
  });

remote: true

, 200 401, {status: 'true'}, , .

action: "create"
commit: "Sign in"
controller: "users/sessions"
user: {
  email: "test@test.cz"
  password: "123"
  remember_me: "0"
}
utf8: ""

.

resource = User.find_for_database_authentication(email: params[:user][:email])

User.find_for_database_authentication

, -

created_at: "2015-05-29T12:48:04.000Z"
email: "test@test.cz"
id: 1
updated_at: "2015-06-13T19:56:54.000Z"

null

,

if resource.valid_password?(params[:user][:password])

, ,

sign_in :user, resource

SessionController

​​

+32

All Articles