我目前正在使用Devise gem处理用户身份验证。
有一些帮助程序方法,它们基本上可以使您在用户访问控制器中的特定路由/视图之前对其进行身份验证。
即,如果您需要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
(通常意味着所有这些方法)可用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句