我正在使用用户和管理员的两个单独模型的设计。我想替换authenticate_user!用我自己的函数auth_user!这样管理员的权限就是用户权限的超集。我还编写了一个函数actions_permitted,可以更轻松地调用skip_before_filter。我在ApplicationController.rb中添加的代码如下。例如,我在控制器中使用它:actions_permitted:public => [:show],user:[:new,:create]。Rails 3.2&Devise:custom authenticate_user!验证用户和管理员
但是,代码没有按预期运行:某些操作未正确验证,而其他操作需要管理员以管理员始终具有用户功能时也以用户身份登录。一些谷歌搜索后,我怀疑这个问题可能是,当继承的模型调用actions_permitted,它发生在ApplicationController级别而不是在特定的模型。我还发现很多在Stackoverflow上推荐的CanCan,尽管如果你能帮助我实现它,我宁愿坚持actions_permitted的简单语法!
# app/controllers/application_controller.rb
#
# call with :user and :public defined as either :all or an array
# of symbols that represent methods. Admins can do everything that users
# can (by definition of auth_user!).
def self.actions_permitted(hash)
# first process exceptions to user authentication
if hash[:public] == :all
# skip all filters and return
skip_before_filter :auth_user!
skip_before_filter :authenticate_admin!
return
elsif hash[:public].kind_of?(Array)
# skip user authentication for methods in :public array
skip_before_filter :auth_user!, only: hash[:public]
end
# then process exceptions to admin authentication
if hash[:user] == :all
# users can do everything, so skip all admin authenticatoin
skip_before_filter :authenticate_admin!
elsif hash[:user].kind_of?(Array)
if hash[:public].kind_of?(Array)
# Join the two arrays and skip admin authentication as not to filter
# actions allowed by the public or by users
skip_before_filter :authenticate_admin!, only: (hash[:user] | hash[:public])
else
# otherwise, simply skip admin authentication for actions allowed by users
skip_before_filter :authenticate_admin!, only: hash[:user]
end
elsif hash[:public].kind_of?(Array)
# skip admin authentication for actions allowed by the public
skip_before_filter :authenticate_admin!, only: hash[:public]
end
end
# checks if user OR admin is authenticated.
def auth_user!(opts = {})
# return (authenticate_user! || authenticate_admin!)
return (env['warden'].authenticated?(:user) ||
env['warden'].authenticated?(:admin))
end