Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user signed in before any action in Rails

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.
like image 759
yerassyl Avatar asked Jun 07 '15 09:06

yerassyl


3 Answers

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]
like image 135
Florent Ferry Avatar answered Oct 14 '22 17:10

Florent Ferry


You can also create your own helper method.

In your users_controller.rb, create a before_action filter

class UsersController < ApplicationController
    before_action :logged_in_user
    ...
end

and in your session_helper.rb

module SessionHelper
   # Returns true if the user is logged in, false otherwise.
   def logged_in?
       !current_user.nil?
   end

   # Confirms a logged-in user.
   def logged_in_user
      unless logged_in?
         flash[:danger] = "Please log in."
         redirect_to login_url
      end
   end

end
like image 12
Archie Reyes Avatar answered Oct 14 '22 15:10

Archie Reyes


If you want to check whether user is signed for every action in the application, you have to put the filter in the application controller. You can do this for a specific controller also.

You can use the devise method:

class SomeController < ApplicationController
  before_action :authenticate_user!
  ...
end

You can create your own filter also:

class SomeController < ApplicationController
  before_action :my_authentication
  ... 
  def my_authentication
     if user_signed_in? 
        # do something ...
     else 
        # do something else ...
     end
  end
end
like image 2
webster Avatar answered Oct 14 '22 16:10

webster