3

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?

Dave
  • 28,833
  • 23
  • 113
  • 183
nexequ
  • 321
  • 5
  • 16
  • You could look into [TinyAuth](https://github.com/dereuromark/cakephp-tinyauth) as it solves this without having to write code in your controllers :) – mark Nov 18 '18 at 16:00

2 Answers2

11

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)

Dave
  • 28,833
  • 23
  • 113
  • 183
0

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);
}
ManG
  • 1
  • 1