检查用户是否在Rails中的任何操作之前登录

时间:2015-06-07 09:16:06

标签: ruby-on-rails ruby-on-rails-4

我想在任何控制器操作之前执行一些函数来检查用户是否已登录。我正在使用devise以便我可以使用is_signed_in?,但我必须将if else条件设置为控制器中的每个方法。

我想要的是这样的东西:



#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



 所以我希望这个方法在任何动作(或一组动作)之前执行,如果为false则重定向登录,或者如果为真,则执行该动作。

5 个答案:

答案 0 :(得分:17)

Devise附带了一些有用的内置助手。

在您的情况下,您感兴趣的是authenticate_user!。在Devise文档中查看controller filters and helpers

您可以使用此方法过滤控制器中的操作,以确保只有登录用户可以处理控制器中的给定操作或所有操作,否则如果用户未登录,则他将重定向到登录页面。

before_action :authenticate_user!

before_action :authenticate_user!, only: [:show]

答案 1 :(得分:9)

您也可以创建自己的帮助方法。

users_controller.rb中,创建一个before_action过滤器

class UsersController < ApplicationController
    before_action :logged_in_user
    ...
end

并在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

答案 2 :(得分:2)

如果要检查用户是否为应用程序中的每个操作签名,则必须将过滤器放在应用程序控制器中。您也可以为特定控制器执行此操作。

您可以使用devise方法:

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

您也可以创建自己的过滤器:

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

答案 3 :(得分:1)

您使用的是devise吗?您可以使用现有过滤器:

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

如果没有,请在应用程序控制器中创建过滤器并将其添加到所需的控制器中:

  class SomeController < ApplicationController
    before_filter :my_auth_filter
    ...
  end

答案 4 :(得分:1)

您可以将此方法添加到ApplicationController

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

在调用任何操作之前使用它。像这样,

class AdminsController < ApplicationController
  before_action :user_is_logged_in
  ...
end