Search code examples
cakephpcakephp-2.0cakephp-2.x

How to apply Role based authorization after login in cakephp 2.7?


I'm new on cakephp . I have implementd a code for login and I m trying to providing Role based action for differecnt users. Such as I have a table in which i store id and role (Admin,Normal,SubAdmin). I want that super admin can add delete update and edit and view everones record. Admin can only edit and delete add users and cant delete/edit his record. How could i achieve this.


Solution

  • you can do by use this code

    In your App Controller :

    class AppController extends Controller {
    public $components =array(
                       'Session',
                        'Flash',
                       'Auth'=>array(
    
                       'authenticate' => array(
                        'Form' => array(
                        'fields' => array('username' => 'Email','password'=>'Passward'),
                        )),
                        'loginRedirect'=>array('controller'=>'Users','action'=>'index'),
                        'logoutRedirect'=>array('controller'=>'Users','action'=>'login'),
                         'authError'=>"You Can't access this page",
                         'authorize' => array('controller')
                      )
                        );
    
     public function beforeFilter()
     {
         $this->Auth->allow('index');
     }
     public function isAuthorized($user)
     {
            return  true;
     }
     }
    

    In your Users Controller:

    class UsersController extends AppController {
    
     public $helpers = array('Html', 'Form','Session','Flash');
     public function beforeFilter()
     {   
         parent::beforeFilter();
         $this->Auth->allow('add');
     }
     public function isAuthorized($user) {
        // The owner of a post can edit and delete it
        if (in_array($this->action, array('edit', 'delete'))) {
    
        switch ($user['Role']) {
          case "Super user":
            return true;
            break;
          case "Admin":
            if($user['id']==$this->request->params['pass'][0])
            {
                return false;
            }
            else
            {
                return true;
            }
            break;
          default:
              return false;
        }
    
        }
        return true;
    }