CakePHP允许,使用Auth拒绝访问

时间:2013-02-13 10:13:59

标签: cakephp cakephp-2.0 cakephp-2.1

我有一个模型'events',它拥有自己的数据+用户ID。如何仅向该事件所属的用户授予访问权限?

1 个答案:

答案 0 :(得分:3)

您可以在视图方法的开头添加一个检查,以查看Authenticated用户ID是否与事件的ID匹配。如果没有,请使用“拒绝访问”闪存消息将其重定向。例如,在您的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.
     */
}