簡體   English   中英

帶有設計和cancan的嵌套資源授權

[英]Nested resource authorization with devise and cancan

如何正確授權與devise和cancan嵌套的資源? 我已經從文檔中實施了建議的步驟,但是沒有成功。

此問題涉及能力模型無法使用devise和cancan gem從嵌套資源的第三層獲取用戶ID。 但是,我可以從第二層獲取用戶ID。 任何幫助是極大的贊賞!

我有這樣的嵌套資源:

  resources :users do
    resources :clients do
      resources :positions
    end
  end

  resources :clients do
    resources :positions
  end

  resources :users do
    resources :positions
  end

  resources :users
  resources :clients
  resources :positions 

position模型控制器一起使用以下方法:

class PositionsController < ApplicationController
  before_filter :grab_client_from_client_id
  load_and_authorize_resource :user
  load_and_authorize_resource :client, through: :user, shallow: true
  load_and_authorize_resource :position, through: :client, except: [:index], shallow: true
  ...
end

Capacity.rb文件:

class Ability
  include CanCan::Ability

  def initialize(user)

    user ||= User.new # guest user (not logged in)

    if user.has_role? :admin
      can :manage, :all
    elsif user.has_role? :management
      can [:create, :read, :update], :all
    else
      can :read, :all, user_id: user.id
    end

  end
end

這導致非管理員/非管理用戶收到以下錯誤:

undefined method 'user_id' for #<User:0x5227d40>

顯然,某些設置不正確。 我已經遍歷了每一個gem的文檔,並在各處尋找解決方案。

我還將在下面提供我的模型關系。


class User < ActiveRecord::Base
  has_many :clients
  has_many :positions, through: :clients
  resourcify
  ...
end


class Client < ActiveRecord::Base
  resourcify
  has_many :checklogs
  has_many :positions
  belongs_to :user
end


class Position < ActiveRecord::Base
  resourcify
  belongs_to :client
  delegate :user, to: :client, allow_nil: true
end

問題出在這一行:

can :read, :all, user_id: user.id

當您檢查用戶是否可以閱讀某些內容時,它會檢查您嘗試閱讀的內容。

由於您的控制器中包含以下行:

load_and_authorize_resource :user

您嘗試授權的資源是用戶。

您的能力將比較user.user_idcurrent_user.id 用戶沒有user_id ,這就是錯誤的出處。

根據您的代碼,除非您是管理員或管理員,否則我懷疑您只希望用戶能夠閱讀其內容。

您可以通過以下方式實現此目的:

if user.has_role? :admin
  can :manage, :all
elsif user.has_role? :management
  can [:create, :read, :update], :all
else
  can :read, User, id: user.id
  can :read, Client, user_id: client.id
  can :read, Position, client: { user_id: user.id }
end

這樣,用戶只能訪問與其有關系的那些模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM