0
我有一個模型「事件」,它擁有自己的數據+用戶ID。我如何僅授予對事件所屬的用戶的訪問權限?CakePHP允許,拒絕使用認證的訪問
我有一個模型「事件」,它擁有自己的數據+用戶ID。我如何僅授予對事件所屬的用戶的訪問權限?CakePHP允許,拒絕使用認證的訪問
您可以在view方法的開頭添加一個檢查,以查看Authenticated用戶標識是否匹配該事件的標識。如果不是,則用「拒絕訪問」的消息重新引導它們。例如,在您的EventsController中添加:
public function view($event_id) {
// Make sure the event exists at all
if (!$this->Event->exists($event_id)) {
throw new NotFoundException(__('No such event.'));
}
// Get the event data
$event = $this->Event->findById($event_id);
// Match the authenticated user with the user_id of the event.
if ($this->Auth->User('id') != $event['Event']['user_id']) {
// No match, redirect the user back to the index action.
$this->Session->setFlash(__('This is not your event!'));
$this->redirect(array('action' => 'index'));
}
/**
* If this point is reached, the user is the owner of the event.
* The rest of your logic goes below this point.
*/
}
好的工作,可能有幫助 – 2013-02-13 11:30:57
這只是一個完美的答案! Auth組件是否只返回用戶的id或任何字段?我想讓角色爲admin的用戶也可以查看所有事件? – 2013-02-13 13:37:38
@JohhnyP你可以訪問存儲在用戶表中的認證用戶的任何信息,所以如果角色在role_id中設置,只需勾選$ this-> Auth-> User('role_id')'以匹配您的管理員角色ID。 – Oldskool 2013-02-13 14:35:00