Search code examples
cakephpauthenticationroutesprefix

Cakephp 2.x Authentication Prefix admin and agent


Iam writing an application with cakephp where i will have admin and agents where they can login to the system. Admin will have different layout from the agents. I have already create the the users table where i added a role field (admin,agent) ,i added the prefixes in core.php

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

I managed to create the login and the logout for admin, but still iam confused how i should proceed with the rest. For Example i dont understand how beforeFilter() and isAuthorized() functions works. How i can check if user has access to that function or not. Also the redirections if a someone try to access this page domain.com/admin to be redirected to admin/login page .

Thanks.


Solution

  • Use the beforeFilter() to control access to each action, the below example will only allow access to the view and index action - any other action will be blocked :

    $this->Auth->allow('view', 'index');
    

    if you want to allow access to all the actions in your controller , try this in your before filter:

    $this->Auth->allow();
    

    To control who has access to what you could use a simple function in your app controller like so:

    protected function _isAuthorized($role_required) {
              if ($this->Auth->user('role') != $role_required) {
                     $this->Session->setFlash("your message here...");
                     $this->redirect("wherever you want the user to go to...");
                }
       }
    

    In your controller action, eg. admin_delete on the first line you would do the following:

    $this->_isAuthorized('admin');
    

    Finally the redirect works like so:

    $this->redirect(array('controller' => 'home', 'action' => 'dashboard'));
    

    if you are redirecting within the same controller simply do the following:

    $this->redirect('dashboard');
    

    Hope this helps.