在 Rails 中将 Devise 身份验证助手与 `OR` 语句相结合
Combining Devise authenticate helpers with `OR` statements in Rails
我目前正在使用 Devise gem 来处理用户身份验证。
有一些辅助方法基本上允许您在用户访问控制器中的某个 route/view 之前对用户进行身份验证。
即如果您需要 user_type_one
s 登录才能访问 /home
:
class FooController < ApplicationController
before_action :authenticate_user_type_one!
def home
#stuff
end
end
您将如何使指定类型的用户可以访问该页面。
所以如果我有三种类型的用户,user_type_one
、user_type_two
和 user_type_three
,我只希望 user_type_one
s 和 user_type_two
s访问 /home
,我想做这样的事情。
before_action :authenticate_user_type_one! || :authenticate_user_type_two!
Devise 为您处理了很多默认设置,并且做得很好,但是当您需要开始自定义行为时,它可能会变得非常棘手。特别是如果您是 Rails 开发的新手,通常我认为最好只编写自己的自定义方法来手动检查您需要检查的内容。然后,随着您对 Devise 越来越熟悉,您可以慢慢了解它可能具有的内置工具,或者您可以侵入的内部挂钩,以更优雅地获得所需的行为。
具体来说,作为起点,我会尝试编写自定义 before_action:
class FooController < ApplicationController
before_action :authenticate_apple_or_orange_or_pear!
def home
stuff
end
protected
def authenticate_apple_or_orange_or_pear!
unless apple_signed_in? or orange_signed_in? or pear_signed_in?
redirect_to go_away_and_never_return_path, alert: "You're not wanted here."
end
end
end
如果我正确理解您的需求,这应该可以满足您的要求。它检查是否已登录任何所需的帐户类型,如果没有,它将访问者重定向到不同的路径,阻止访问此控制器。
如果这是您跨多个控制器需要的东西,您还可以将此方法定义移动到 application_controller.rb
中,它将对继承自 ApplicationController
的所有控制器可用(通常, 表示全部)。
我目前正在使用 Devise gem 来处理用户身份验证。
有一些辅助方法基本上允许您在用户访问控制器中的某个 route/view 之前对用户进行身份验证。
即如果您需要 user_type_one
s 登录才能访问 /home
:
class FooController < ApplicationController
before_action :authenticate_user_type_one!
def home
#stuff
end
end
您将如何使指定类型的用户可以访问该页面。
所以如果我有三种类型的用户,user_type_one
、user_type_two
和 user_type_three
,我只希望 user_type_one
s 和 user_type_two
s访问 /home
,我想做这样的事情。
before_action :authenticate_user_type_one! || :authenticate_user_type_two!
Devise 为您处理了很多默认设置,并且做得很好,但是当您需要开始自定义行为时,它可能会变得非常棘手。特别是如果您是 Rails 开发的新手,通常我认为最好只编写自己的自定义方法来手动检查您需要检查的内容。然后,随着您对 Devise 越来越熟悉,您可以慢慢了解它可能具有的内置工具,或者您可以侵入的内部挂钩,以更优雅地获得所需的行为。
具体来说,作为起点,我会尝试编写自定义 before_action:
class FooController < ApplicationController
before_action :authenticate_apple_or_orange_or_pear!
def home
stuff
end
protected
def authenticate_apple_or_orange_or_pear!
unless apple_signed_in? or orange_signed_in? or pear_signed_in?
redirect_to go_away_and_never_return_path, alert: "You're not wanted here."
end
end
end
如果我正确理解您的需求,这应该可以满足您的要求。它检查是否已登录任何所需的帐户类型,如果没有,它将访问者重定向到不同的路径,阻止访问此控制器。
如果这是您跨多个控制器需要的东西,您还可以将此方法定义移动到 application_controller.rb
中,它将对继承自 ApplicationController
的所有控制器可用(通常, 表示全部)。