使用 CanCan 指定拒绝访问的原因
我真的很喜欢 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为你可以直接使用 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 ofAbility
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 thecurrent_ability
method that CanCan provides to return the ability for the current user. Then, by providing the samecan?
andcannot?
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 awhy?
method which could identify whichAbility
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.