1
votes

How do I (safely) allow only admins and authors to edit data in CakePHP, without referring to hard-coded group IDs?

I'm using Auth and ACL in my CakePHP 2.4 app, so ordinarily I would just restrict the edit action to admins and moderators, but I also need to allow authors to edit data they've created.

I currently have this in my edit method, which works, but uses hard-coded values, which is bad practice: I set the ACLS to allow edit by default, and the controller redirects if the user is neither author nor admin.

Is there a way to respect the ACL settings (thus avoiding hard-coded group ids), while punching a hole through them for post authors?

if ($this->Auth->user('id') != $this->Post->field('user_id')) {
    if ($this->Auth->user('group_id') > 2) {

    $this->Session->setFlash(__('You are not authorized to edit this post.'), 'flash/error');
    $this->redirect(array('action' => 'index'));
    }
}
2
Take a look at CakePHP's documentation about authorization. It might shed some light on your question. - mathielo

2 Answers

2
votes

You can store authors 'id or name' to enable edition it's own. You can check rows 'admin or author or guest' to check for editing all contents.

http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html#authorization-who-s-allowed-to-access-what

This is already in documentation

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 = $this->request->params['pass'][0];
        if ($this->Post->isOwnedBy($postId, $user['id'])) {
            return true;
        }
    }

    return parent::isAuthorized($user);
}
-1
votes

Follow CakePHP book.

I hope Controller::isAuthorized() and Post::isOwnedBy() in the article is your purpose.