Tag Archives: 2.x

CakePhp 2 Tip#8-Checking User Ownership

cake-logo

Another common task in Cakephp Applications or any Web Application is making sure that a user can only delete items they own otherwise anyone could erase your entire database.

An example you have created a users table and users can create posts, but we need to ensure that User A can only edit and delete posts belonging to them.

Solution: The isAuthorized() function.
This function will check that the user isAuthorized to do what ever action they are about to under take.

Assuming every posts has a user_id as a foreign key, we can check the current logged in user’s Id against the id stored in the post their about to modify and if they match allow and if not deny.

// 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);
}
// app/Model/Post.php
public function isOwnedBy($post, $user) {
    return $this->field('id', array('id' => $post, 'user_id' => $user)) !== false;
}

Entire User Auth Solution and Guide:
https://github.com/cakephp/docs/blob/master/en/tutorials-and-examples/blog-auth-example/auth.rst