简体   繁体   English

使用CanCanCan gem和ActiveAdmin创建授权

[英]Create authorization using CanCanCan gem and ActiveAdmin

I created some rules and one of them is the following: 我创建了一些规​​则,其中一个是以下内容:

can :create, Ticket, { author_id: user.id }

This should allow the currently authenticated user to create tickets only when author_id is equal the user's id. 仅当author_id等于用户ID时,这才应允许当前经过身份验证的用户创建票证。

From rails console I can test that my rule works fine: 从Rails控制台,我可以测试我的规则是否正常工作:

my_user.can? :create, Ticket.new(author: my_user)      # returns true
my_user.can? :create, Ticket.new(author: another_user) # returns false

Considering that I'm using ActiveAdmin, I now need to use my authorization rules with it by using its ActiveAdmin::AuthorizationAdapter . 考虑到我正在使用ActiveAdmin,现在我需要通过使用其ActiveAdmin::AuthorizationAdapter来使用我的授权规则。

One problem I am facing is that whenever I create a "New Ticket" I get access denied. 我面临的一个问题是,每当创建“新票证”时,都会遭到拒绝访问。

I doubled checked what condition is failing and it seems that AA asks for the following: 我仔细检查了什么条件失败了,看来机管局要求以下条件:

my_user.can? :create, Ticket.new # which returns false!

When I believe it should ask for the following instead: 当我认为应该改为以下内容时:

my_user.can? :create, Ticket # which returns true!

Ticket.new has all parameters set to nil: Ticket.new的所有参数均设置为nil:

<Ticket author_id: nil, ..., created_at: nil, updated_at: nil>

that is why my CanCanCan hash condition is failing (author_id = nil is not valid, it should be user_id instead). 这就是为什么我的CanCanCan哈希条件失败的原因(author_id = nil无效,应该是user_id)。

Is there aa possibile fix for this? 是否有可能的解决办法? Maybe I'm setting my CanCanCan rule in the wrong way? 也许我设置的CanCanCan规则设置错误?

ActiveAdmin is also offering a CanCanCan adapter out of the box so I'm wondering how they could have overlooked this. ActiveAdmin还提供了一个开箱即用的CanCanCan适配器,所以我想知道他们怎么可能忽略了这一点。

Based on answer to a similar question: 基于对类似问题的回答:

ActiveAdmin.register Ticket do
  before_build do |ticket|
    ticket.author = current_user
  end
end

This sets the author while creating the new object, which qualifies it to be accessible as configured in the CanCanCan abilities. 这将在创建新对象时设置作者的身份,从而使它具有可以按照CanCanCan功能中的配置进行访问的资格。

@GoGoCarl commented with the relevant question above, but I've modified for the question asked here. @GoGoCarl对上面的相关问题发表了评论,但是我已经修改了此处提出的问题。 Original answer: 原始答案:

https://stackoverflow.com/a/28738827/3353794 https://stackoverflow.com/a/28738827/3353794

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM