2

我正在为用户和管理员使用具有两个独立模型的设计。我想替换authenticate_user!用我自己的功能,auth_user!这样管理员的权限是用户权限的超集。我还写了一个函数,actions_permitted,它可以更容易地调用skip_before_filter。我在 ApplicationController.rb 中添加的代码如下。例如,我在控制器中使用它:actions_permitted :public => [:show], user: [:new, :create]。

但是,代码未按预期运行:某些操作未正确验证,而其他操作则需要管理员也以用户身份登录,而管理员应始终具有用户权限。经过一番谷歌搜索,我怀疑问题可能是当继承模型调用 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
4

1 回答 1

3

原来问题出在 auth_user! 中。对于将来想要使用此代码的任何人,以下是更正:

def auth_user!(opts = {})
  if admin_signed_in?
    authenticate_admin!
  else
    authenticate_user!
  end
end
于 2013-01-09T22:22:58.947 回答