我在 CakePHP 中做策略授權。對于所有 CRUD 方法,我必須測驗用戶是否有權執行它們。所以我創建了該方法以在所有方法中使用:
SchoolsController 中的代碼
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']);
}
我被重定向并收到兩條訊息:“您沒有權限。” “學校已成功撤離。”
這是我的 SchoolPolicy
public function canDelete(IdentityInterface $user, School $school)
{
return $this->isAuthor($user,$school);
}
protected function isAuthor(IdentityInterface $user, School $school)
{
return $school->userId === $user->id;
}
uj5u.com熱心網友回復:
如果你捕捉到一個例外,那么它當然不會停止執行,這就是捕捉它的全部意義所在。如果您隨后從您的方法中回傳一個值(Controller::redirect()將回傳回應物件并相應Location配置了標頭),您將需要對該值執行某些操作,否則它將消失在 void 中,例如:
$response = $this->authorize($school);
if ($response) {
return $response;
}
它在 docs 中有點隱藏,但更簡單的方法是從您的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',
])
);
}
您可能還想考慮使用自定義的未經授權的處理程式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489146.html
標籤:php 例外 蛋糕PHP 试着抓 cakephp-4.x
上一篇:沒有捕捉到例外未定義的行為嗎?
