justin henricks
justin henricks

Reputation: 467

Rails check if Devise has any errors?

I am looking for a way to check if Devise has any errors (invalid credentials etc.) for a before_action method in my ApplicationController. There is code in that method that I need only to run if Devise has no errors.

class ApplicationController < ActionController::Base
   before_action :foo

   def foo
      if !devise_errors?
   end
end

Upvotes: 1

Views: 230

Answers (2)

demir
demir

Reputation: 4709

You can check credential errors like this:

class ApplicationController < ActionController::Base
  before_action :foo

  def foo
    if !devise_errors?
  end
  ..
  private

  def devise_errors?
    login_params = devise_parameter_sanitizer.sanitize(:sign_in)
    email = login_params.dig(:email)
    password = login_params.dig(:password)
    user = User.find_by(email: email)
    return true if user.blank?

    !user.valid_password?(password)
  end
  ..
end

Upvotes: 1

pixelearth
pixelearth

Reputation: 14610

Do you mean sign in errors? Wouldn't you only need this in the session controller?

You could check the flash messages...

But you might be better off checking in Warden:

Warden::Manager.warden_callback do |user, auth, opts|
  # code 
end

Upvotes: 1

Related Questions