phplistyiicontrolsrole-based

Access Control Lists or Role-based access control in yii


hy i wanna understand what it the best methode to use and how if there is a simple exemple because i can't specify whitch rol to give to witch personne

public function accessRules()
{
    return array(
        array('allow',  // allow authenticated  to perform 'index' and 'view' actions
            'actions'=>array('index','view'),
            'users'=>array('@'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
            'actions'=>array('create','update'),
            'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
            'actions'=>array('admin','delete'),
            'users'=>array('admin'),
        ),
        array('deny',  // deny all users
            'users'=>array('*'),
        ),
    );
}

Solution

  • You can specify based on user roles like for editor you want show only edit user features and for publisher you can provide only access to block and unblock the user and so on. For eg: We have used the below code in our project

    public function accessRules()
        {
            if(isset(Yii::app()->user->role) && Yii::app()->user->role == "superadmin"){
                $arr = array('create','update','admin','delete','block','help','download','forgot');
            } elseif(isset(Yii::app()->user->role) && Yii::app()->user->role == "admin") {
                $arr = array('help','download','forgot');
            } elseif(isset(Yii::app()->user->role) && Yii::app()->user->role == "editor") {
                $arr = array('update');
            } elseif(isset(Yii::app()->user->role) && Yii::app()->user->role == "publisher") {
                $arr = array('block');
            } else {
                $arr = array('');
            }
            return array(
                array('allow', // allow admin user to perform 'admin' and 'delete' actions
                    'actions'=>$arr,
                    'users'=>array('@'),
                ),
                array('deny',  // deny all users
                    'users'=>array('*'),
                ),
            );
        }
    

    Like wise you want to show a page only to registered user and some of the pages for both registered and guest users. We can do the same in the accessRules() function

    To allow all users

    array('allow', 
                'actions'=>array('create','update'),
                'users'=>array('*'),
            ),
    

    To allow only registered users

    array('allow', 
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
    

    To create restriction based on usernames

    array('allow',
                'actions'=>array('create','update'),
                'users'=>array('username1','username2'),
            ),