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. 
    */ 
} 
+0

好的工作,可能有帮助 – 2013-02-13 11:30:57

+0

这只是一个完美的答案! Auth组件是否只返回用户的id或任何字段?我想让角色为admin的用户也可以查看所有事件? – 2013-02-13 13:37:38

+0

@JohhnyP你可以访问存储在用户表中的认证用户的任何信息,所以如果角色在role_id中设置,只需勾选$ this-> Auth-> User('role_id')'以匹配您的管理员角色ID。 – Oldskool 2013-02-13 14:35:00