Ruby-on-rails – Check if user signed in before any action in Rails

ruby-on-railsruby-on-rails-4

I want to execute some function before any controller action to check if the user is signed in. I am using devise so that I can use is_signed_in?, but I have to put if else condition to every method in the controller.

What I want is to have something like this:

#some_controller.rb
before_action :is_signed_in?

def is_signed_in?
   if !user_signed_in?
      redirect_to new_user_session_path
   else 
      ..proceed to the action intended to call
   end
end

So I want this method to execute before any action (or some set of actions) and redirect to sign in if false or let that action to be executed if true.

Best Solution

Devise is shipped with some useful built-in helpers.

In your case, one that interested you is authenticate_user!. Take a look at controller filters and helpers in Devise documentation.

You can filter your actions in your controller with this method to ensure only logged-in users can process a given action or all actions in a controller, else if user isn't logged-in then he is redirect to login page.

before_action :authenticate_user!

before_action :authenticate_user!, only: [:show]