try catch捕获异常,但运行之后的代码仍然cakephp

kuhbmx9i  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(145)

我在CakePHP中进行策略授权。对于所有的CRUD方法,我必须测试用户是否有权执行它们。因此,我创建了该方法,以便在所有方法中使用:
学校控制器中的代码

private function authorize(School $s){
    try{
        $this->Authorization->authorize($s);
    } catch(ForbiddenException $e){
        $this->Flash->error("You don't have permission.");
        return $this->redirect(['controller' => 'Schools', 'action' => 'index']);
    }
}

我正在为一个没有权限的用户测试代码。这应该可以工作,但是调用此方法后的代码仍然被调用。

public function delete($id = null) {
        $school = $this->Schools->get($id);
        $this->authorize($school);

        $this->request->allowMethod(['post', 'delete']);
        if ($this->Schools->delete($school)) {
            $this->Flash->success(__("School has been successfully removed."));
        } else {
            $this->Flash->error(__("The school could not be deleted. Please try again."));
        }

        return $this->redirect(['action' => 'index']);
    }

我被重定向,并收到两条消息:“您没有权限。”“学校已成功删除。”
这是我的学校政策

public function canDelete(IdentityInterface $user, School $school)
    {
        return $this->isAuthor($user,$school);
    }
    protected function isAuthor(IdentityInterface $user, School $school)
    {
        return $school->userId === $user->id;
    }
bd1hkmkf

bd1hkmkf1#

如果你捕捉到一个异常,那么它当然不会停止执行,这就是捕捉它的全部意义。如果你从你的方法返回一个值(Controller::redirect()将返回带有相应配置的Location头的响应对象),你需要对这个值做些什么,否则它将消失在void中,例如:

$response = $this->authorize($school);
if ($response) {
    return $response;
}

它在文档中有一点隐藏**,但是更简单的方法是从authorize()方法中抛出一个重定向异常。另外,如果你实际上没有使用任何被禁止的异常和它所包含的信息,那么你可以简单地使用can()方法,它返回一个布尔值,例如:

if (!$this->Authorization->can($s)) {
    $this->Flash->error("You don't have permission.");

    throw new \Cake\Http\Exception\RedirectException(
        \Cake\Routing\Router::url([
            'controller' => 'Schools',
            'action' => 'index',
        ])
    );
}

您可能还需要考虑使用自定义未授权处理程序

相关问题