2012-06-20 23 views
0

我在我的控制器中有這個。CakePHP:正確的方法來安全地刪除記錄

public function delete($id) { 
    if($this->request->is('get')) { 
     throw new MethodNotAllowedException(); 
    } 

    $this->Memberlist->id = $id; 
    if (!$this->Memberlist->exists()) { 
     throw new NotFoundException(__('Invalid list.')); 
    } 
    if ($this->Memberlist->delete()) { 
     $this->Session->setFlash(__('List deleted.'), 'success'); 
     return $this->redirect(array('action'=>'index')); 
    } 
    $this->Session->setFlash(__('List was not deleted.'), 'error'); 
    return $this->redirect(array('action'=>'index')); 
} 

我的模型看起來是這樣的:(屬於關聯)

<?php 

class Memberlist extends AppModel { 
    public $name = 'Memberlist'; 
    public $belongsTo = array(
      'Account' => array(
      'className' => 'Account', 
      'foreignKey' => 'account_id' 
     ) 
    ); 

在我的觀點之一,我有這樣的事情:

echo $this->Form->postLink('Delete', 
        array('action' => 'delete', $list['Memberlist']['id']), 
        array('class'=>'btn-mini btn', 'confirm' => 'Are you sure?')); 

它創建一個像這樣的HTML:

<form id="post_4fe15efc0d284" method="post" style="display:none;" name="post_4fe15efc0d284" action="/Grid/memberlists/delete/9"> 
<input type="hidden" value="POST" name="_method"> 
<input id="Token1627936788" type="hidden" value="8756f7ad21f3ab93dd6fb9a4861e3aed4496f3f9" name="data[_Token][key]"> 
<div style="display:none;"> 
</form> 
<a class="btn-mini btn" onclick="if (confirm('Are you sure?')) { document.post_4fe15efc0d284.submit(); } event.returnValue = false; return false;" href="#">Delete</a> 

問題是,當我使用Firebug(或任何開發人員工具)更新action="/Grid/memberlists/delete/9"中的ID時,我幾乎可以刪除任何東西!甚至從一個不同的帳戶。即使我打開了安全組件。

什麼是正確的方法來做到這一點?我正在考慮針對當前登錄用戶的account_id檢查account_id。但是我只是好奇,如果CakePHP有一些開箱即用的解決這個問題?

回答

3

您可以將beforeDelete回調添加到您的模型中,並查詢數據庫並檢查用戶是否被允許刪除記錄,或者是他的所有者。

+0

我是新來CakePHP的,發現這個答案是很容易實現。在模型中做到這一點也很有意義。 – wenbert

2

要真正阻止用戶完成不同的操作,如刪除不屬於用戶的內容,應該使用Auth Component

我假設帳戶模型存儲用戶數據。您需要按照食譜中的教程進行操作,但我強調了如何拒絕刪除權限。

你isAuthorized方法會是這個樣子:

public function isAuthorized($account) { 
    // The owner of a post can edit and delete it 
    if (in_array($this->action, array('edit', 'delete'))) { 
     $memberListId = $this->request->params['pass'][0]; 
     if ($this->MemberList->isOwnedBy($memberListId, $account['id'])) { 
      return true; 
     } 
    } 

    // Default deny 
    return false; 
} 

,這將走在型號:

public function isOwnedBy($memberList, $account) { 
    return $this->field('id', array('id' => $memberList, 'account_id' => $account)) === $post; 
} 
相關問題