![](/img/trans.png)
[英]cakephp rest api POST request invokes index() rather than add()
[英]Protecting a method in CakePHP using POST rather than GET
我想保護應用程序中的某些方法,例如發布,取消發布和關閉。 保護並不是指用戶授權,而是指以某種方式調用方法的能力。
我已經考慮過強制使用POST而不是GET來調用方法,以便一個人不能只是將URL粘貼到地址中(即使我可以檢查執行此操作的用戶的ID)。 但是,這意味着對於每個方法調用,將每個按鈕包裝為不同的形式。
另外,我可以使用GUID允許GET方法,但要確保它只允許正確的人執行該功能。
有什么想法嗎?
到目前為止,我已經嘗試過:
function publish($id = null)
{
$post = $this->Post->find('first',array('conditions'=>array('Post.id'=>Tiny::reverseTiny($id))));
if ($this->request->is('post') || $this->request->is('put'))
{
$this->Post->id = $post['Post']['id'];
$this->Post->saveField('status', 1);
$this->Session->setFlash('Your post has been published!');
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id'])));
}
else
{
die('GET METHOD NOT ALLOWED');
}
}
但是如上所述,這意味着該方法的鏈接/按鈕將需要采用包含對該方法的操作調用的形式。 如果我有幾種方法,我將需要幾種形式...
干杯
我考慮過的一種方法是允許get方法,然后將帖子的用戶ID與登錄的用戶ID進行比較,如下所示:
if ($this->request->is('get'))
{
if($post['Post']['user_id'] != $this->Auth->user('id'))
{
$this->Session->setFlash('You don\'t have permission to edit that post!');
$this->redirect(array('controller' => 'posts', 'action' => 'index'));
}
else
{
$this->Post->id = $post['Post']['id'];
$this->Post->saveField('status', 1);
$this->Session->setFlash('Your post has been published!');
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id'])));
}
}
這是好習慣嗎?
(在這里假設CakePHP 2.0)
首先,不要在“發布/獲取”支票上打電話給死亡。 拋出異常,cake中的異常很棒( Exceptions ):
if (!$this->request->is('get')) {
throw new MethodNotAllowedException();
}
Cake還提供了一種生成鏈接以通過模板刪除(通過發布)的方法。
<?php echo $this->Form->postLink('Delete',
array('action' => 'delete', $post['Post']['id']),
array('confirm' => 'Are you sure?'));
?>
編輯(鏈接): postLink
這是我在堆棧溢出中的第一個答案。 希望對您有所幫助。
如果只想允許某些用戶執行該功能,則聽起來您需要ACL或某種形式的權限。 您不使用已發布內容( if($post['Post']['user_id'] != $this->Auth->user('id'))
)的原因是,您最終會在整個代碼庫中以許多功能復制該代碼。 那太草率了。
但是,您只想確保提交是以特定方式提交的,那么拋出錯誤方法就是您的最佳選擇。 而且您應該能夠將提交保持在相同的函數內,如下所示:
public function publish($id = null) {
if (!$id || !$this->request->is('get') || !$this->request->is('post') || !$this->request->is('put')) {
throw new MethodNotAllowedException();
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->Post->id = $post['Post']['id'];
$this->Post->saveField('status', 1);
$this->Session->setFlash('Your post has been published!');
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id'])));
}
if ($this->request->is('get')) {
// perform your get request here
}
}
用最少的代碼$ this-> request-> allowMethod('post');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.