我查看了文档并做了一些搜索,但我没有看到全能用户(超级用户)级别的选项,或者如何创建一个选项。如何将全能用户级别添加到权威
有没有人看到或创建了这样做的原因?即时通讯认为它可能会绑定到核心认证系统,但我不知道该在哪里搭配。
许多感谢..
我查看了文档并做了一些搜索,但我没有看到全能用户(超级用户)级别的选项,或者如何创建一个选项。如何将全能用户级别添加到权威
有没有人看到或创建了这样做的原因?即时通讯认为它可能会绑定到核心认证系统,但我不知道该在哪里搭配。
许多感谢..
要做到这一点是让你的授权检查对于已指定的用户或角色返回true的唯一途径“超级用户”。因此,它应该是这样的:
def update?
*normal authorization logic* or is_superuser?
end
def edit?
*normal authorization logic* or is_superuser?
end
#etc...
private
def is_superuser?
# configure how to determine who the super users are and return true/false
end
您可以定义在ApplicationPolicy
的is_superuser?
私有方法假设你继承了应用策略类一级的政策;否则,您需要在每个策略中定义它。
我发现了一种方法,使用ApplicationPolicy的继承一点DRYer。我使用别名访问方法,并且在调用它们之前绑定超级用户测试。如果用户是超级用户,我只需返回true即可。在初始化之前,我需要将实例方法定义为别名。
ALIAS_PREFIX = '__original_'
def initialize(user, record)
@user = user
@record = record
[:index?,:show?,:create?,:new?, :update?, :edit?, :destroy?].each do |access_method|
alias_name = ALIAS_PREFIX+access_method.to_s
aliasing_original_method(access_method,alias_name)
self.class.send(:define_method, access_method) do |*args|
superuser? ? (return true) : send(alias_name, *args)
end
end
end
private
def superuser?
#whatever you want to define a super user
end
def aliasing_original_method(old_name, new_name)
self.class.send(:alias_method, new_name, old_name)
self.class.send(:private, new_name)
end
而在[AnyFile]政策我做的:
def initialize(user, record)
super(user, record)
end
这将确保在子策略的每个方法的真实回报。
[更新]
第一个解决方案是有点乱,而我的红宝石(和最后期限)知识不允许我去更远推动它。无论如何,我找到了另一种方式。由于我总是改变用户的角色,所以我在ApplicationPolicy中实现了一个for_roles方法。
def for_roles(*args,&block)
return true if superuser?
if args.include?(:all) || (@user.role_symbols & args).any?
block.call
else false
end
end
然后,在任何政策,比如,你可以做
for_roles(:client_admin,:technician) do
#any rule computation, DB request you want
end
#or
for_roles(:all) do
#any rule computation, DB request you want
end
感谢nikkon266 ..我有一种感觉,这是做到这一点的唯一方法。我希望我错过了一个在Pundit中的自建方法。 –