是否可以使用 cancan 引发 Access Denied 以外的异常?
Is it possible to raise an exception other than Access Denied with cancan?
我用康康来控制权限。
我想将 return 目的地 (404,403) 更改为特定条件
但是,除了 CanCan::AccessDenied
之外,我不知道如何使用 cancan
进行例外处理
如果您有想法,请告诉我。
下面是我的代码。(如果状态为真,我想 return 和 404,否则我想 return 403)
型号
#app/models/ablity.rb
if current_user.status
can :show, Organization # 404
else
can :show, Organization # 403
end
控制器
def index
authorize! :show, Organization
rescue CanCan::AccessDenied => e
render_403 # if status true
render_404 # if status false
end
我做了一些挖掘,看起来 CanCan 不支持您需要的异常粒度。
所以...为什么不在您的控制器中也使用 current_user.status
?
def index
authorize! :show, Organization
rescue CanCan::AccessDenied => e
if current_user.status
render_403
else
render_404
end
end
(或者,如果重复 code/logic 是一个问题,请将它们都放在您在能力 class 和控制器中都调用的方法中。)
然后根据您的能力 class 将代码段简化为以下内容:
can :show, Organization
顺便说一句,CanCan 尚未得到维护 in years. You may want to switch to the more actively maintained CanCanCan(但我认为您需要上述相同的解决方案)。
此外,如果您最终根据用户的状态(无论该状态可能传达什么)显示不同的页面,您可能会无意中泄露用户 and/or non-users 不应该泄露的信息看,类似于 here.
的解释
我用康康来控制权限。 我想将 return 目的地 (404,403) 更改为特定条件
但是,除了 CanCan::AccessDenied
之外,我不知道如何使用 cancan
如果您有想法,请告诉我。
下面是我的代码。(如果状态为真,我想 return 和 404,否则我想 return 403)
型号
#app/models/ablity.rb
if current_user.status
can :show, Organization # 404
else
can :show, Organization # 403
end
控制器
def index
authorize! :show, Organization
rescue CanCan::AccessDenied => e
render_403 # if status true
render_404 # if status false
end
我做了一些挖掘,看起来 CanCan 不支持您需要的异常粒度。
所以...为什么不在您的控制器中也使用 current_user.status
?
def index
authorize! :show, Organization
rescue CanCan::AccessDenied => e
if current_user.status
render_403
else
render_404
end
end
(或者,如果重复 code/logic 是一个问题,请将它们都放在您在能力 class 和控制器中都调用的方法中。)
然后根据您的能力 class 将代码段简化为以下内容:
can :show, Organization
顺便说一句,CanCan 尚未得到维护 in years. You may want to switch to the more actively maintained CanCanCan(但我认为您需要上述相同的解决方案)。
此外,如果您最终根据用户的状态(无论该状态可能传达什么)显示不同的页面,您可能会无意中泄露用户 and/or non-users 不应该泄露的信息看,类似于 here.
的解释