3
votes

I would like to authorize users based on few roles. All visitors should be able to reach method show. So I wrote in AppController:

public function beforeFilter(Event $event) {
    $this->Auth->allow(['show']);
}

It works.

In initialize() method of AppController I've got also:

$this->loadComponent('Auth', [
    'authorize' => 'Controller'
]);

I would like to allow logged users with role "user" to reach all "index", and "add" methods, so I wrote in AppController:

public function isAuthorized($user) {
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
if (isset($user['role']) && $user['role'] === 'user') {
$this->Auth->allow(['index', 'logout', 'add']);
}

return false;
}

Admin can reach all methods as expected. User logged with role "user" can't reach "index" or "add" method. How can I fix this?

2
You could look into TinyAuth as it solves this without having to write code in your controllers :) - mark

2 Answers

11
votes

Instead of using your logic to add additional Auth allows, just use the logic to determine if they're in an action they're allowed, by checking the action, and return true if they're authorized.

public function isAuthorized($user) {

    // Admin allowed anywhere
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }

    // 'user' allowed in specific actions
    if (isset($user['role']) && $user['role'] === 'user') {

        $allowedActions = ['index', 'logout', 'add'];
        if(in_array($this->request->action, $allowedActions)) {
            return true;
        }

    }
    return false;
}

(obviously this code could be shortened to your liking, but it shows the concept)

0
votes

I find this solution to be great and easier to maintain.

//in all controllers that you want to restrict access
public function isAuthorized($user)
{
    //an array since we might want to add additional roles
    $possibleRoles = array('admin');
    return $this->confirmAuth($user['role'], $possibleRoles);
}

//in AppController
public function confirmAuth($userRole, $allowedRoles)
{
    return in_array($userRole, $allowedRoles);
}