0

因为我一直在努力寻找一个好的方法来制作这个大约两个星期,所以我认为问问是个好主意。

我有两个User角色:editoradmin。每个editor人都有一个Region分配给他的 s 范围,通过$hasAndBelongsToMany

在应用程序中,我还有一个模型Event,每个模型都有一个Region,通过一个region_id。我想确保每个人都editor可以查看、编辑、删除和做其他事情,只有那些EventRegion他的任务中。用户admin当然可以编辑任何东西。

如何在我的 CakePHP 模型和控制器中实现这一点?

4

1 回答 1

1

您可以editEventsController. 找到事件的区域,然后检查登录的编辑器是否是该区域的编辑器。您需要做的就是确保当用户登录时,他/她的角色保存在AuthComponent的会话中。例如:

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));
        }
    }
}

所以基本上在你做任何其他逻辑之前,你检查用户是否是编辑器,如果是,他关联的区域是否与当前事件的区域匹配。如果它没有设置一个 flash 消息并且用户被踢回view事件的视图。

于 2013-01-09T19:06:52.000 回答