传递参数时,CakePHP被授权不能正常工作

时间:2013-05-16 13:57:29

标签: php cakephp authorization cakephp-2.0

如果记录ID不属于用户,我正在使用isAuthorized拒绝访问方法。配置文件可以包含许多文档和文档属于一个配置文件:

控制器/ DocumentsController.php

public function add($id = null) {
    if ($this->request->is('post')) {
        $this->request->data['Document']['profile_id'] = $id;
        $this->request->data['Document']['user_id'] = $this->Auth->user('id');
        $this->Document->create();
        if ($this->Document->save($this->request->data)) {
            $this->Session->setFlash(__('The document has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The document could not be saved. Please, try again.'));
        }
    }
}

public function isAuthorized($user) {
    if ($this->action === 'index') {
        return true;
    }

    if (in_array($this->action, array('view', 'add', 'edit', 'delete'))) {
        $document_id = $this->request->params['pass'][0];
        if ($this->Document->isOwnedBy($document_id, $user['id'])) {
            return true;
        }
    }

    return parent::isAuthorized($this->Auth->user());
}

型号/ Document.php

public function isOwnedBy($document, $user) {
    return $this->field('id', array('id' => $document, 'user_id' => $user)) === $document;
}

我通过Cake链接助手从我的个人资料视图中将profile id作为$id传递给docments/add

查看/概况/ view.ctp

echo $this->Html->link('New Document',
    array('controller' => 'documents', 'action' => 'add',$profile['Profile']['id'])
);

当我点击来自profiles/view的新文档时发生的情况是它发送请求但不重定向,只刷新页面,或者重定向回profiles/view,不知道哪个。我的第一个猜测是因为我没有在profile id内的isAuthorized回调中定义DocumentsControllerisOwnedBy返回false。有关如何在isAuthorized DocumentsController内获取个人资料ID的任何建议吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

解决方案相对容易。当使用带有来自另一个控制器的参数的isAuthorized时,请务必引用正确的模型。

if ($this->Document->Profile->isOwnedBy($document_id, $user['id'])) {
    return true;
}