0
在CakePHP 3 Blog Tutorial所有權授權,用戶有條件地授權使用操作,如編輯和刪除基於與下面的代碼所有權: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]);
}
我一直在試圖實施類似的東西爲我自己的桌子。例如,我有一個付款表,它通過幾個不同的表格鏈接到用戶,如下所示:
- 用戶 - >客戶 - >預訂 - >付款。
每個外鍵:
user_id
在客戶表=Users->id
(用戶hasOne顧客)- 在預訂
customer_id
表=Customers->id
(客戶的hasMany登記) 在付款表
booking_id
=Bookings->id
(Booking has Many Payment)
我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]);
}
我不確定如何通過不同的鏈接表來決定所有權歸屬。
- 目前,如果支付預訂#123的客戶只需更改網址,以便爲預訂#111支付費用,前提是預訂存在於數據庫中。
- 此外,預訂ID被傳遞給購物車功能(因爲客戶正在爲特定預訂付款)。例如:如果客戶爲Booking#123付款,則URL = localhost/project/payments/cart/123。提交購物車後,會創建一個新的付款條目。
另外,關於getParam和isOwnedBy方法,在我的編輯鼠標懸停在此顯示:
Method 'getParam' not found in \Cake\Network\Request
Method 'isOwnedBy' not found in App\Model\Table\PaymentsTable
不過,我已經通過了整BlogTutorial並且無法在模型中使用或設置其他任何getParam或isOwnedBy。
在你的'PaymentsController :: isAuthorized()',怎麼會第三條件'如果(in_array($這個 - >請求 - >行動,['車'])){當第二個(相同)條件成立時,會被滿足嗎? –
啊耶忘了。我刪除它。無論所有權如何,嘗試訪問購物車頁面時,我現在都將'Method getParam不存在'視爲Cake錯誤。 – mistaq
已修復,稍後會回覆。 – mistaq