簡體   English   中英

不能阻止訪問

[英]CanCan not preventing access when it should

當我以其他用戶身份登錄時訪問users/1/edit不會引發AccessDenied錯誤,我也不知道為什么:

  authorize_resource only: [:edit, :update]
  def edit
    @user = User.find(params[:id])
  end
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      redirect_to @user
    else
      render 'edit'
    end
  end

能力等級:

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new

    can :read, :all
    can :create, User
    can :create, Group

    can :update, User, id: user.id
  end
end

如果我將authorize_resource更改為load_and_authorize_resource則它將按預期工作。 但這肯定不相關嗎?

您的代碼僅授權用戶訪問編輯和更新操作,而不授權@user對象

您必須像這樣手動授權對象

嘗試這個,

def edit
  @user = User.find(params[:id])
  authorize! :update, @user
end

def update
  @user = User.find(params[:id])
  authorize! :update, @user
  if @user.update_attributes(params[:user])
   redirect_to @user
  else
   render 'edit'
  end
end

我面臨着和您一樣的問題,但對我來說,我正在使用康康設計。 因此,在我的控制器中,我將

 before_filter :authenticate_user!, :except=>[:create]

它將驗證除創建以外的用戶。

def index
    @user = User.all
    authorize! :index, @user
    respond_to do |format|
       format.html # index.html.erb
       format.xml  { render :xml => @user }
    end
end

您想要授權用戶訪問權限的每個控制器功能,您都可以這樣做,看來您需要做很多工作,只需將每一個控制器放入需要授權的功能中,而不是僅使用load_and_authorize_resource,但是希望可以從我已經完成的工作中得到一點幫助。 這是資源:https://github.com/ryanb/cancan/wiki/authorizing-controller-actions。 如果您得到答案以及為什么load_and_authorize_resource無法正常工作,也可以在此處發布:)

我還沒有答案(到目前為止)為什么會發生這種情況,但是我遇到了基本上相同的問題。 我的情況與眾不同之處僅在於手動授權每個操作(而不是依賴“授權資源”或“ load_and_authorize”是關鍵)。

我也遇到了這個問題,這就是我所發現的。

如果我:update動作中正確讀取源代碼 ,則load_and_authorize執行find_by加載資源,然后調用authorize! 在上面。 但是,在應用了傳入參數之后,我看不到它在哪里對其進行授權。 (如果我讀錯了,請糾正我。)

我看到的用例是某人編輯資源,然后在編輯中更新資源中的值,使其不再有資格在保存時通過授權。 (當然,我正在設置UI來幫助避免這種情況,但是顯然我仍然想保護資源。)運行功能測試,我能夠設置我希望不通過控制器授權的屬性:update操作,大概是因為檢查是在解析屬性之前進行的。

到目前為止,我解決該問題的方法是調用authorize! 設置屬性后再次出現,這意味着我不能使用update_attributes因為我要在保存之前進行授權:

class FooController < ApplicationControlller

  load_and_authorize_resource

  def update

    # slurp the mass assignable params
    @foo.attributes = params[:foo]

    # set some other params
    @foo.some_other_attr = 'bar'

    # authorize again, now that we have updated the params
    authorize! :update, @foo

    if @foo.save!
      flash[:notice] = I18n.t(...)   
      respond_with(@foo)
    # ...
    end 
  end 
end

一種替代方法是創建一個before_filter,自己加載@foo實例,然后按上述方式調用authorize,但這實際上並不能使事情變得更加整潔,恕我直言。 這將節省一個授權! 呼叫。

我對其他人如何處理此事感到好奇。 我是CanCan的新手,所以我想我做錯了什么。 :)

暫無
暫無

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

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