Sarah
Sarah

Reputation: 516

How to retrieve information when linking models through a table in CakePHP 3.0?

I'm trying to set up a user access model based on the one in the CakePHP blog tutorial (http://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html), but with Roles in a separate table, and linked to users by a UserRoles table.

I currently have the following in Model/Table/UsersTable.php:

    $this->belongsToMany('Roles', [
        'through' => 'UserRoles'
    ]);

and the following in Model/Table/RolesTable.php:

    $this->belongsToMany('Users', [
        'through' => 'UserRoles'
    ]);

and the following in Model/Table/UserRolesTable.php:

    $this->belongsTo('Users', [
        'foreignKey' => 'user_id'
    ]);
    $this->belongsTo('Roles', [
        'foreignKey' => 'role_id'
    ]);

I have view, create, and administrator roles created. I'm trying to figure out how to check a user's role or roles in AppController.php. This is the simple example given for when the role incorporated into the user object:

public function isAuthorized($user)
{
    // Admin can access every action
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }

    // Default deny
    return false;
}

I'm not sure how to access the User object and get the user's role by the user's ID from the AppController file. Since the user is not linked to the role directly, how would I access the role information from an IsAuthorized function? How would I do a lookup to retrieve the user's role when it is linked by another table? Thank you!

Upvotes: 0

Views: 305

Answers (1)

When setting up the AuthComponent in your controller, make sure you tell it to fetch related data:

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'contain' => ['Roles']
            ]
        ]
    ]);
}

Upvotes: 4

Related Questions