Matt Hough
Matt Hough

Reputation: 1101

Devise: Redirect to different path on failed user authentication

I am struggling to find a way to customize authenticate_user! so that instead of redirecting to the login page, it will redirect to a beta signup page if a user is not logged in.

Is there a way I can change the redirect path to a beta signup page conditionally by adding something like the below to the authenticate_user! method?

ENV['BETA_MODE'] ? redirect_to beta_signup_path : redirect_to login_path

Upvotes: 1

Views: 1642

Answers (2)

Matt Hough
Matt Hough

Reputation: 1101

I found a fix for this first mentioned here https://groups.google.com/forum/#!topic/plataformatec-devise/qymDM9u9n6Y.

I defined a custom authentication failure class in config/initializers/devise.rb like so:

config.warden do |manager|
  manager.failure_app = CustomAuthenticationFailure
end

After doing that I created a file called custom_authentication_failure.rb in /vendor. The contents of that file looked like this:

class CustomAuthenticationFailure < Devise::FailureApp
  protected

  def redirect_url
    ENV['BETA_MODE'] ? beta_signup_path : new_user_session_path
  end
end

I also needed to add this in config/application.rb, because it wasn't already there:

config.autoload_paths += %W(#{config.root}/vendor) 

Upvotes: 2

Ismail Akbudak
Ismail Akbudak

Reputation: 305

You need to add custom devise controller to your app. You can do it as follow;

In config/routes.rb file;

devise_for :users, controllers: { registrations: "registrations" }

Add following controller content to app/controllers/registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  protected

  def after_sign_up_path_for(resource)
    ENV['BETA_MODE'] ? beta_signup_path : login_path
  end
end

More: https://github.com/plataformatec/devise/wiki/how-to:-redirect-to-a-specific-page-on-successful-sign-up-(registration)

Upvotes: 1

Related Questions