因为我一直试图找到一个很好的方法来做这件事大约两个星期,所以我认为这只是一个好主意。
我有两个User
个角色:editor
和admin
。 editor
通过Region
为$hasAndBelongsToMany
分配了Event
个范围。
在应用中,我还有一个模型Region
,每个模型都有region_id
,来自editor
。我想确保每个Event
只能查看,编辑,删除和执行其他任务Region
中admin
的其他内容。 {{1}}用户当然可以编辑任何内容。
如何在CakePHP模型和控制器中最简单地实现这一点?
答案 0 :(得分:1)
您可以在edit
的{{1}}方法的前几行处理此问题。找到事件的区域,然后检查登录的编辑器是否是该区域的编辑器。您需要做的就是确保当用户登录时,他/她的角色会保存在EventsController
的会话中。例如:
AuthComponent
所以基本上在你做任何其他逻辑之前,你检查用户是否是编辑器,如果是,那么他所关联的区域是否与当前事件的区域匹配。如果没有设置flash消息,则用户将被踢回事件的public function edit($event_id = null) {
if($this->Auth->user('role') == "editor") {
// User is logged in as editor, check if the Event region matches his regions.
$event = $this->Event->findById($event_id); // Get the event
$user = $this->Event->User->findById($this->Auth->user('id')); // Get the user (Assuming an Event belongsTo user, otherwise you'll have to load the model first).
if(!array_search($event['Event']['region_id'], $user['User']['Region'])) {
// The event's region wasn't found in the Regions for the User, deny access
$this->Session->setFlash(__('You are not authorized to edit this event.'));
$this->redirect(array('action' => 'view', $event_id));
}
}
}
视图。