2011-04-15 50 views
0

我想改變我的編輯動作,以便用戶只能編輯帖子,如果它是他們自己的。動作權限

下面是編輯動作之前,我改變了它:

function edit($id = null) { 
    $this->Post->id = $id; 
    if (empty($this->data)) { 
     $this->data = $this->Post->read(); 
    } else { 
     if ($this->Post->save($this->data)) { 
      $this->Session->setFlash('Your post has been updated.'); 
      $this->redirect(array('action' => 'index')); 
     } 
    } 
} 

然後在這裏就是我試圖這樣做,但沒有成功:

function edit($id = null) { 
    if ($this->Auth->user('id') == $this->Post->user_id) { 
     $this->Post->id = $id; 
     if (empty($this->data)) { 
      $this->data = $this->Post->read(); 
     } else { 
      if ($this->Post->save($this->data)) { 
       $this->Session->setFlash('Your post has been updated.'); 
       $this->redirect(array('action' => 'index')); 
      } 
     } 
    } else { 
     $this->Session->setFlash('You are not authorized to edit that post.'); 
     $this->redirect(array('action' => 'index')); 
    } 
} 

任何人都知道我可以實現我的所需的功能?使用CakePHP的automagic有沒有更簡單的方法?

回答

0
public function edit($id) { 
    $post = $this->Post->find('first', array(
     'conditions' => array('Post.id' => $id, 'Post.user_id' => $this->Auth->user('id')), 
     'recursive' => -1 
    )); 
    if (!$post) { 
     $this->cakeError('error404'); 
    } 

    if ($this->data) { 
     $this->data['Post']['id'] = $id; 
     if ($this->Post->save($this->data)) { 
      $this->Session->setFlash('Your post has been updated.'); 
      $this->redirect(array('action' => 'index')); 
     } 
    } else { 
     $this->data = $post; 
    } 
}