gpt4 book ai didi

ruby-on-rails - Rails 3.2 & Devise : custom authenticate_user! 验证用户和管理员

转载 作者:行者123 更新时间:2023-12-04 05:16:11 28 4
gpt4 key购买 nike

我正在使用带有两个独立模型的用户和管理员设计。我想替换authenticate_user!使用我自己的函数 auth_user!这样管理员的权限是用户权限的超集。我还编写了一个函数actions_permitted,它可以更容易地调用skip_before_filter。我在 ApplicationController.rb 中添加的代码如下。例如,我通过以下方式在 Controller 中使用它: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

最佳答案

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

def auth_user!(opts = {})
if admin_signed_in?
authenticate_admin!
else
authenticate_user!
end
end

关于ruby-on-rails - Rails 3.2 & Devise : custom authenticate_user! 验证用户和管理员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14234706/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com