Reputation: 15692
Because I have been trying to find a good way to make this for about two weeks, I thought it'd be a good idea to just ask.
I have two User
roles: editor
and admin
. Every editor
has a range of Region
s assigned to him, via $hasAndBelongsToMany
.
In the app I also have a model Event
, each of which has a Region
, via a region_id
. I want to make sure that every editor
may view, edit, delete and do other things only those Event
s that are in a Region
of his assignment. A admin
user may of course edit anything.
How can I implement this with the least fuss in my CakePHP models and controllers?
Upvotes: 0
Views: 134
Reputation: 34837
You can handle this in first few lines of the edit
method of your EventsController
. Find the region of the event and then check if the logged in editor is editor of that region. All you'd need to do is make sure that when a user logs in, his/her role is saved in the AuthComponent
's session. For example:
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));
}
}
}
So basically before you do any other logic, you check if the user is an editor and if so, if the regions he's associated to matches the region for the current event. If it doesn't a flash message is set and the user is kicked back to the view
view for the event.
Upvotes: 1