2014-02-20 41 views
0

我正在寫一個模塊,限制用戶只能在他們的資源上執行操作。說,只有房客1 belongs_to他/她,房東才能做GET /tenants/1Rails:是否可以使用HTTP請求(Devise,protect_from_forgery)更新外鍵?

在租戶控制器我的代碼

respond_to do |format| 
    if @tenant.update_attributes(params[:tenant]) 
    format.html { redirect_to @tenant, notice: 'Tenant was successfully updated.' } 
    format.json { render json: @tenant } 
    # else ... 
end 

以下塊的更新操作是否有可能爲landlord在他tenant更新外鍵,讓tenant的記錄可能移動到其他landlord的帳戶?我使用Devise在應用程序控制器中使用protect_from_forgery進行身份驗證。我可以從瀏覽器中的HTML頁面源提取authenticity_token,但帶有該標記的cURL請求失敗 - 警告:無法驗證CSRF令牌的真實性。

有沒有辦法在HTTP請求的記錄上僞造外鍵?我是否需要檢查在params散列中傳遞的外鍵?

回答

0

如果你不想允許這樣做,你應該使用強參數。

在你的控制器:

def tenant_params 
    params.require(:tenant).permit(:name, :address ...) # make sure :landlord_id is not there 
end 

而在你的更新動作:

respond_to do |format| 
    if @tenant.update_attributes(tenant_params) 
    ... 

這樣一來,即使在情況不太可能發生,有人成功招數用戶訪問一個頁面,以便闡述這種意願實際上可以繞過csrf標記並將一個landlord_id參數發送到更新操作,因此該參數將被忽略,因爲它顯式不被允許。

還有另一種方法,例如,如果你的字段列表太長處理或您自己的任何其他原因,而不是使用強大的參數,你可以從後弦刪除參數:

在您的更新操作中:

params[:tenant].except!(:landlord_id) if !params[:tenant][:landlord_id].nil? #don't forget to use the "bang" (!) 
respond_to do |format| 
    if @tenant.update_attributes(params[:tenant]) 
    .... 
+0

感謝您的建議 - 我喜歡它。 – sakovias

+0

然後你可以給它一個正面的投票,或者選擇它作爲答案。謝謝。 –

+0

我選擇了這個作爲答案,但由於我的低調,我無法贊成。乾杯! – sakovias

相關問題