0

isAuthorized如果记录 ID 不属于用户,我将用于拒绝对方法的访问。配置文件可以有多个文档,并且文档属于一个配置文件:

控制器/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());
}

模型/文档.php

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

我正在通过 Cake 链接助手从我的个人资料视图中传递profile idas $idto :docments/add

查看/配置文件/view.ctp

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

当我单击 New Document from 时会发生什么profiles/view,它发送请求但不重定向,只是刷新页面,或者它重定向回profiles/view,不确定是哪个。我的第一个猜测是因为我没有profile idisAuthorized回调中定义DocumentsControllerisOwnedBy所以返回错误。关于如何在其中获取个人资料 ID 的任何isAuthorized建议DocumentsController

提前致谢!

4

1 回答 1

0

解决这个问题相对容易。将 isAuthorized 与来自另一个控制器的参数一起使用时,请务必引用正确的模型。

if ($this->Document->Profile->isOwnedBy($document_id, $user['id'])) {
    return true;
}
于 2013-05-16T23:58:02.293 回答