使用 CanCan 指定拒绝访问的原因

发布于 2024-09-26 09:27:09 字数 203 浏览 3 评论 0原文

我真的很喜欢 Rails 授权 gem CanCan。但是,我发现自己对某些权限有多个条件,并且我希望能够向用户提供不同的错误消息,具体取决于他或她被拒绝访问的原因。

CanCan 是否有针对此类行为的机制?我很难找到它。我是否必须自己分叉并添加该行为?

I really like the Rails authorization gem CanCan. However, I find myself having multiple conditions on certain privileges, and I'd like to be able to give different error messages to the user, depending on why he or she has been denied access.

Does CanCan have a mechanism for such behavior? I'm having trouble finding it. Would I have to fork it and add that behavior myself?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帝王念 2024-10-03 09:27:09

我不认为你可以直接使用 CanCan 来做到这一点。它实际上只是提供了一种方式来说明用户是否可以做某事。

我想知道您是否可以通过定义多个能力子类来检查权限来以非典型方式使用它。默认实现是为当前用户创建一个Ability 实例并对其进行询问。

如果您创建了Ability子类的集合来反映您想要检查的不同类型的访问权限,那么您可以依次询问每个子类用户是否可以或不可以执行某些操作。第一个拒绝许可的人将被用来生成您的特定错误消息。

您实际上只需要创建一个总体能力类来组合 Ability 子类的集合,并在 CanCan 提供的 current_ability 方法中创建它,以返回当前的能力用户。然后,通过在您的类上提供相同的 can?cannot? 方法,它将以与正常功能相同的方式工作,但您可以将其扩展到提供一个why? 方法,该方法可以识别哪个Ability 子类拒绝了权限并生成不同的错误消息。

实际上,您还必须提供一个新的 authorize! 实现,以使其返回您想要的错误消息。

抱歉,答案很长,基本上是 - 你必须自己做。

I don't think you can do it with CanCan straight out of the box. It only really provides a way for saying whether a user can or cannot do something.

I wonder if you could use it in an atypical way though by defining multiple Ability subclasses to check permissions. The default implementation is to create an instance of Ability for the current user and interrogate that.

If you created a collection of Ability subclasses to reflect the different kinds of access you want to check you could then ask each in turn whether the user can or cannot do something. The first to refuse permission would then be used to generate your specific error message.

You'd only really have to create an overarching ability class to combine the collection of Ability subclasses and create that in the current_ability method that CanCan provides to return the ability for the current user. Then, by providing the same can? and cannot? methods on your class it will work in the same way as the normal abilities but you'd be able to extend it to provide a why? method which could identify which Ability subclass refused permission and generate a different error message as a result.

Actually, you'd have to provide a new implementation of authorize! too to make it return the error message you wanted.

Sorry, long answer which is basically - you'd have to do it yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文