在CakePHP 3博客教程中,用户有条件地被授权使用以下代码,根据所有权使用编辑和删除等操作:
public function isAuthorized($user)
{
// All registered users can add articles
if ($this->request->getParam('action') === 'add') {
return true;
}
// The owner of an article can edit and delete it
if (in_array($this->request->getParam('action'), ['edit', 'delete'])) {
$articleId = (int)$this->request->getParam('pass.0');
if ($this->Articles->isOwnedBy($articleId, $user['id'])) {
return true;
}
}
return parent::isAuthorized($user);
}
public function isOwnedBy($articleId, $userId)
{
return $this->exists(['id' => $articleId, 'user_id' => $userId]);
}
我一直试图为我自己的表实现类似的东西。例如,我有一个付款表,它通过以下几个不同的表链接到用户:
每个的外键:
用户-
My AppController的初始化函数:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth',[
'authorize' => 'Controller',
]);
$this->Auth->allow(['display']); //primarily for PagesController, all other actions across the various controllers deny access by default
}
在我的工资控制器中,我有以下内容
public function initialize()
{
parent::initialize();
}
public function isAuthorized($user)
{
if (in_array($this->request->action,['view', 'edit', 'index', 'add']
return (bool)($user['role_id'] === 1); //admin functions
}
if (in_array($this->request->action,['cart'])) {
return (bool)($user['role_id'] === 2) //customer function
}
if (in_array($this->request->action, ['cart'])) {
$bookingId = (int)$this->request->getParam('pass.0');
if ($this->Payments->isOwnedBy($bookingId, $user['id'])) {
return true;
}
}
return parent::isAuthorized($user);
}
public function isOwnedBy($bookingId, $userId)
{
return $this->exists(['id' => $bookingId, 'user_id' => $userId]);
}
我不确定如何通过链接不同的表来确定所有权。
另外,关于getParam和isOwnedBy方法,在我的编辑器中悬停在它们上面会显示:
方法'getParam'未在\Cake\Network\Request中找到
在App\Model\Table\PaymentsTable
然而,我已经浏览了整个博客教程,在模型中找不到使用或设置getParam或isOwnedBy的其他地方。
在PaymentsController中的IsAuthorized函数中:
if (in_array($this->request->action, ['cart'])) {
$id = $this->request->getParam('pass'); //use $this->request->param('pass') for CakePHP 3.3.x and below.
$booking = $this->Payments->Bookings->get($id,[
'contain' => ['Artists']
]);
if ($booking->artist->user_id == $user['id']) {
return true;
}
}