Check if user has been signed before any action in Rails

I want to execute some function before any controller action to check if the user is signed. I use devise to use is_signed_in ?, but I need to put an if else condition for each method in the controller.

I want 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 be executed before any action (or some set of actions) and redirected to the input if false, or let this action be executed if true.
+6
source share
5 answers

Devise comes with some useful built-in helpers.

In your case, you are interested in authenticate_user! . Take a look at the filters and controller assistants in the development documentation.

You can filter your actions in your controller using this method to ensure that only registered users can process the task or all actions in the controller, otherwise, if the user is not registered, he will be redirected to the login page.

 before_action :authenticate_user! before_action :authenticate_user!, only: [:show] 
+12
source

You can also create your own helper method.

In users_controller.rb create a before_action filter

 class UsersController < ApplicationController before_action :logged_in_user ... end 

and in 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 
+8
source

If you want to check if the user is signed for each action in the application, you must place the filter in the application controller. You can do this for a specific controller.

You can use the devise method:

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

You can also create your own filter:

 class SomeController < ApplicationController before_action :my_authentication ... def my_authentication if user_signed_in? # do something ... else # do something else ... end end end 
+2
source

Do you use devise ? You can use an existing filter:

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

If not, create your filter in the application controller and add it to the necessary controllers:

  class SomeController < ApplicationController before_filter :my_auth_filter ... end 
+1
source

You can add this method to your ApplicationController.

 def user_is_logged_in if !session[:current_user] redirect_to login_path end end 

Use it before invoking any action. In this way,

 class AdminsController < ApplicationController before_action :user_is_logged_in ... end 
0
source

Source: https://habr.com/ru/post/988640/


All Articles