In order to implement role base access you have to exted the default implementation of Yii, which comes only with user authentication (user is logged or user is guest).
In order to start with role based access, I recommend you to start by implementing your user class by extending the Yii CWebUser class.
Something like:
class WebUser extends CWebUser {
/**
* cache for the logged in User active record
* @return User
*/
private $_user;
/**
* is the user a superadmin ?
* @return boolean
*/
function getIsSuperAdmin(){
return ( $this->user && $this->user->accessLevel == User::LEVEL_SUPERADMIN );
}
/**
* is the user an administrator ?
* @return boolean
*/
function getIsAdmin(){
return ( $this->user && $this->user->accessLevel >= User::LEVEL_ADMIN );
}
/**
* get the logged user
* @return User|null the user active record or null if user is guest
*/
function getUser(){
if( $this->isGuest )
return null;
if( $this->_user === null ){
$this->_user = User::model()->findByPk( $this->id );
}
return $this->_user;
}
}
As you can see User::LEVEL_SUPERADMIN
and User::LEVEL_ADMIN
are provided by CWebUser. Then in your site controller accessRules() put something like:
// Get the current user
$user = Yii::app()->user;
function accessRules(){
return array(
//only accessable by admins
array('allow',
'expression'=>'$user->isAdmin',
),
//deny all other users
array('deny',
'users'=>array('*').
),
);
}
In order to use your new class with role based access, add it in the config/main.php file as an application component:
'components'=>array(
'user'=>array(
//tell the application to use your WebUser class
'class'=>'WebUser'
),
),
In your views, you can see how it works by using:
if(Yii::app()->user->isAdmin){
echo 'Administrator!';
}
if(Yii::app()->user->isSuperAdmin){
echo 'SuperAdmin!';
}
You have to manage the database table for users, and maybe add fields to store the user role constant. Further readings on Role Base Access are:
To continue reading about the code provided in answer, go here.
Update
In order to perform the redirect as you mention, try:
// collect user input data
if(isset($_POST['LoginForm'])) {
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
// If you just want to run the view
$this->render('dashboard',array('model'=>$model));
// If you want to reander the action inside the controller
// $this->redirect( array("site/dashboard") );
}
// display the login form
$this->render('login',array('model'=>$model));
}
Note that dashboard.php file must be placed inside /protected/views/site
folder.