R X
R X

Reputation: 281

CakePHP Complicated authentication (specific user roles to specific controllers/areas)

I'm trying to build a small web app that will have several areas:

  1. Users area
  2. Admins area

I'm using the Auth component and checking after login the Auth->user('role') but this won't prevent a "normal user" typing the admin path in the URL and accessing it (he's logged in). Naturally the admins should be able to access any area but that's not my current problem :)

What is the best way of managing and more importantly implementing these kind of permissions/authentication?

Thanks!

Upvotes: 0

Views: 806

Answers (2)

Tim Joyce
Tim Joyce

Reputation: 4517

I would use the isAuthorized function in your controller

Sample like this:

class PostsController extends AppController {

    public function isAuthorized() {
        if($this->Auth->user('role_id' != '1')) return false;
    }
}

and in your AppController beforeFilter() add

    $this->Auth->authorize = 'Controller';

Upvotes: 0

AKKAweb
AKKAweb

Reputation: 3807

There is ACL. However, I would discourage anyone from using ACL if they can stay away from it. Role Base Authentication is certainly good and easy to implement. They way you are starting out is correct, however, you need to enable admin routing in the core.php file.

Configure::write('Routing.prefixes', array('admin'));

Once that is done, the coding is setup accurately and authentication is inplace, only users with the role of admin will be able to access any admin section, such as http://www.yoursite.com/admin/users

Most magic for the Role Base Authentication to be successfull is done in the AppController class.

Just to give you an example, I would setup the AppController.php file this way:

public $components = array(
    'Cookie',
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'userModel' => 'User',
                'fields' => array(
                    'username' => 'username',
                    'password' => 'password'
                )
            )
        ),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'home'),
        'authorize' => array('Controller')
    )
);


public function isAuthorized($user){        
    if(isset($user['role']) && $user['role'] === 'admin'){
        return true;
    }
    return false;
}

If you want to have an admin layout and a members general layout, you can do so in either the beforeFilter() or beforeRender() functions.

Upvotes: 1

Related Questions