Allowing admins and author to edit or delete data
How to allow only admins and authors to edit or delete data in CakePHP, cause my site author can edit all others post. How to solve this ? I’m using Auth and ACL in my CakePHP application and i permit only my admin and editor user group to edit a post but i also need to permit the author to edit his/her post which they created.
Finally i got a solution in cakephp site, i stated bellow:
Step 1: Add a user id column in your posts table
ALTER TABLE posts ADD COLUMN user_id INT(11);
Step 2: Modify in Post add action so that current user id is save at post save time
// app/Controller/PostsController.php public function add() { if ($this->request->is('post')) { //Added this line $this->request->data['Post']['user_id'] = $this->Auth->user('id'); if ($this->Post->save($this->request->data)) { $this->Session->setFlash(__('Your post has been saved.')); return $this->redirect(array('action' => 'index')); } } }
Step 3: Modify your AppController like bellow:
// app/Controller/AppController.php public $components = array( 'Session', 'Auth' => array( 'loginRedirect' => array('controller' => 'posts', 'action' => 'index'), 'logoutRedirect' => array( 'controller' => 'pages', 'action' => 'display', 'home' ), 'authenticate' => array( 'Form' => array( 'passwordHasher' => 'Blowfish' ) ), 'authorize' => array('Controller') // Added this line ) ); public function isAuthorized($user) { // Admin can access every action if (isset($user['role']) && $user['role'] === 'admin') { return true; } // Default deny return false; }
Step 4: Add isAuthorized function in post controller
// app/Controller/PostsController.php public function isAuthorized($user) { // All registered users can add posts if ($this->action === 'add') { return true; } // The owner of a post can edit and delete it if (in_array($this->action, array('edit', 'delete'))) { $postId = (int) $this->request->params['pass'][0]; if ($this->Post->isOwnedBy($postId, $user['id'])) { return true; } } return parent::isAuthorized($user); }
Step 5: Now add isOwnedBy action in your post model
// app/Model/Post.php public function isOwnedBy($post, $user) { return $this->field('id', array('id' => $post, 'user_id' => $user)) !== false; }
All done, your system is now will check every edit and delete action time is the user is an admin, editor and author user or others.