Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Devise Ajax login Catching Error Message

I am under:
Rails 3.0.9
Devise 1.4.7
jquery-ujs

What have I done?...
1) I have set up the sign-in form with data-remote="true".
2) I have set up the sign-in jquery handlers:

('form#user-reg-form')
    .bind("ajax:beforeSend", function(evt, xhr, settings){
    })
    .bind("ajax:success", function(evt, data, status, xhr){
      $('#comments').append(xhr.responseText);

    })
    .bind('ajax:complete', function(evt, xhr, status){
    })
    .bind("ajax:error", function(evt, xhr, status, error){
      try {
        errors = $.parseJSON(xhr.responseText);
      } catch(err) {
        errors = {message: "Please reload the page and try again"};
      }
      errorText = "There were errors with the submission: \n<ul>";

      for ( error in errors ) {
        errorText += "<li>" + error + ': ' + errors[error] + "</li> ";
      }

      errorText += "</ul>";

      // Insert error list into form
      $form.find('div.validation-error').html(errorText);
    });

3) I have redefined the session controller like this:

  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
    sign_in(resource_name, resource)
    return render :json => { :success => true, :content => current_user.email }
  end

  def failure
    return render:json => {:success => false, :errors => ["Login failed."]}
  end

4) I have set my the route.rb file:

devise_for :users, :controllers => {:sessions => "sessions"}

Everything works...but when I pass wrong email or password I have uncaught message from the User model (maybe from Devise) "email or password is wrong". But I want to catch this message and put it in json object something like this return render:json => {:success => false, :errors => ////email or password is wrong////}

Proble is: :recall doesn't work. It looks like that Warden.authenticate! doesn't see my failure method

like image 361
Lesha Pipiev Avatar asked Oct 09 '22 10:10

Lesha Pipiev


1 Answers

The solutions was very simple )
I have to set in config/initializers/devise.rb:

config.http_authenticatable_on_xhr = false
config.navigational_formats = [:html, :json]
like image 116
Lesha Pipiev Avatar answered Oct 12 '22 11:10

Lesha Pipiev