【问题标题】:Is it possible to raise an exception other than Access Denied with cancan?除了使用 cancan 拒绝访问之外,是否可以引发异常?
【发布时间】:2020-10-03 20:40:33
【问题描述】:

我用 cancan 控制权限。 我想将返回目的地(404,403)更改为特定条件

但是,除了CanCan::AccessDenied 和 cancan 之外,我不知道如何破例

如果你有什么想法,请告诉我。

下面是我的代码。(如果状态为真,我想返回404,否则我想返回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

【问题讨论】:

    标签: ruby-on-rails cancan


    【解决方案1】:

    我进行了一些挖掘,但 CanCan 似乎不支持您需要的异常粒度。

    那么...为什么不在您的控制器中也使用current_user.status

    def index
      authorize! :show, Organization
    rescue CanCan::AccessDenied => e
      if current_user.status
        render_403
      else
        render_404
      end
    end
    

    (或者,如果担心重复的代码/逻辑,请将它们都放在您在能力类和控制器中调用的方法中。)

    然后将能力等级中的 sn-p 简化为以下内容:

    can :show, Organization
    

    顺便说一句,CanCan 尚未维护 in years。您可能希望切换到维护更积极的CanCanCan(但我认为您需要上述相同的解决方案)。

    此外,如果您最终根据用户的状态(无论该状态可能传达什么)显示不同的页面,您可能会无意中泄露用户和/或非用户不应该看到的信息,类似于解释的内容here.

    【讨论】:

    • 我明白没有办法。感谢您的详细建议。 “user.status”作为示例进行了解释以简化解释。实际的代码比这更复杂。所以,我认为在 abity 类中定义它会更简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2012-05-19
    • 2011-04-02
    相关资源
    最近更新 更多