Rails

Redirect To Specific Page If User Is Not Logged In

Posted by Weston Ganger on October 09, 2015

In Devise, when you want to authenticate a user before they can access anything in your controller or application you must add this line to your controller:


before_filter :authenticate_user!

This will redirect the user to the default login page if they are not logged in

But what if you want to redirect them to a different page? By overwriting the method in your application controller:


### app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  ...
private
  def authenticate_user!
    if user_signed_in?
      super
    else
      redirect_to your_path, notice: "Please Login to view that page!"
    end
  end
end

If you are using authenticate_user! in your application controller then you are probably only showing the root page without authenticating the user, in which case you need to add an if to the end of the redirect_to statement, otherwise you will get an infinite redirect loop


redirect_to your_path, notice: "Please Login to view that page!" if request.original_fullpath != your_path


Related External Links:


Posted in Rails and Tagged with rails devise authentication 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts