Devise - Redirected to page if account isn't c

2019-05-20 16:42发布

问题:

I'm trying to redirect the user if their account hasn't been confirmed. So this involves two parts of the code:

  1. Redirect the user after they first create the account
  2. Redirect them if they try to sign in before confirming the account

I need help with the second.

The first I was able to do by putting in after_inactive_sign_up_path_for(resource) in my custom RegistrationsController. I've tried to do the same for a SessionsController, but it didn't work. What do I need to over write in order to properly redirect the user if they haven't confirmed the account yet?

回答1:

You may have to create a custom warden strategy and check if the account needs confirmation. Something of this sorts:

# config/initializers/my_strategy.rb
Warden::Strategies.add(:my_strategy) do 
  def valid? 
    true
  end 

  def authenticate! 
    u = User.find_for_authentication(:email => params[:email])
    if u.nil? || !u.valid_password?(params[:password])
      fail(:invalid)
    elsif !u.confirmed?
      fail!("Account needs confirmation.")
      redirect!("your_root_url")
    end
  else
    success!(u)
  end    
end

#config/initializers/devise.rb
config.warden do |manager|  
  manager.default_strategies(:scope => :user).unshift :my_strategy
end

This assumes the username and password are passed in the request as params. You can look at the database_authenticable strategy for an example of how Devise deals with sign-in authentication by default.