Reputation: 161
I have a model 'events' that holds its own data + user id. How do I grant access only to the user to whom the event belongs?
Upvotes: 0
Views: 618
Reputation: 34837
You can just add a check at the beginning of your view method to see if the Authenticated user id matches that of the event. If not, redirect them back with an "access denied" flash message. For example, in your EventsController add:
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.
*/
}
Upvotes: 3