在CakePHP 3 Blog Tutorial中,用户有条件授权使用以下代码根据所有权使用编辑和删除等操作:
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]);
}
我一直在尝试为自己的表实现类似的功能。例如,我有一个Payments表,它通过几个不同的表链接到Users,如下所示:
每个外键:
user_id
= Users->id
(User hasOne Customer)customer_id
= Customers->id
(客户有多个预订)booking_id
= Bookings->id
(预订有多笔付款)我的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
}
在我的PaymentsController中,我有以下
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方法,将鼠标悬停在我的编辑器中会显示:
Method 'getParam' not found in \Cake\Network\Request
Method 'isOwnedBy' not found in App\Model\Table\PaymentsTable
但是,我已经浏览了整个BlogTutorial,并且找不到在模型中使用或设置getParam或isOwnedBy的任何其他地方。
答案 0 :(得分:0)
在PaymentsController中的IsAuthorized函数中:
{{1}}