How to Custom Devise Ajax Authentication

1. Add Session and Register Controller

  • app/controllers/users/sessions_controller.rb        View Code
  • app/controllers/users/registrations_controller.rb  View Code

 

2. Configure Devise To Accept JSON

In config/initializers/devise.rb:

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

 

3. Configure form authentication

Add :remote => true to sign_in (sessions/new.html.haml) and sign_up (registrations/newnew.html.haml) forms:

form_for(resource, :as => resource_name, ..., format: :json, :remote => true) do |f|

4. Config Routes

In config/routes.rb

devise_for :users, :controllers => {registrations: 'users/registrations', sessions: 'users/sessions'}

 

5. Add javascripts to process submit by ajax

Add app/assets/javascripts/devise.js

callbackSubmit: function(page){
  var self = this;

  $(page).find("form").bind("ajax:success", function(e, response, status, xhr){
    if(response.success){
      window.location.reload();        
    }else{
      // Show failed message
    }
  });
}

 

6. Demo and source code

Demo: https://goo.gl/B4uMI6

Code: https://goo.gl/AwoBrR