CanCan - 用户帐户的密钥持有者访问权限

时间:2013-02-28 18:21:30

标签: ruby-on-rails cancan

我正在使用CanCan&设计用户身份验证&权限。

用户可以为其帐户指定一个密钥持有者,该帐户拥有不同的权限。密钥持有者具有名为“access_id”的属性,该属性与他们可以访问的帐户的ID相同。我想要实现的目标如下:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user

    if user.admin?
      can :manage, :all
    elsif user.keyholder?
      can :read, Folder do |folder|
        folder.try(:user) == user.access_id
      end 
    else
      can :create, :all
      can :manage, :all do |all|
        all.try(:user) == user
      end
    end



  end
end

但是使用此代码,密钥持有者无法访问他们被提名访问的帐户。如何纠正代码才能实现这一目标?谢谢!

1 个答案:

答案 0 :(得分:0)

你可以尝试

folder.user_id == user.access_id

假设密钥持有者已登录。

这样

user.keyholder? => true
user => keyholder
user.access_id => id of user who did nominate current_user
folder.user_id => id of folder owner

修改

如果您还希望密钥持有者也访问他/她的文件夹:

( folder.user_id == user.access_id ) || ( folder.user_id == user.id )

但是这个更好,把它从if / else语句中删除,这样任何人,(keyholder或普通用户)都可以访问他/她自己的文件夹。

def initialize(user)
user ||= User.new # guest user

# every one reads his own folder.. or you can copy this to wherever you want
can :read, Folder do |folder|
  folder.user_id == user.id
end 

if user.admin?
  can :manage, :all
elsif user.keyholder?
  can :read, Folder do |folder|
    # but keyholder accesses even more
    folder.user_id == user.access_id
  end 
else
  can :create, :all
  can :manage, :all do |all|
    all.try(:user) == user
  end
end
end

另外,您也可以定义can:多次读取keyholder。像:

elsif user.keyholder?
  can :read, Folder do |folder|
    folder.user_id == user.access_id
  end 
  can :read, Folder do |folder|
    folder.user_id == user.id
  end 
else