![](/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.