I’m developing a common application, which consists of admin and public part. How can I use different sessions for the admin and the public users so the use of
Yii::app()->user->login($identity,$duration)
will log the proper user for the proper part of the website (i.e. the admin to be logged in the admin only and the public user to be logged in the public part only, btw I’m using 2 different login forms)? If I leave the way it is I have to rewrite accessRules() for all the controllers in the admin module to restrict access from all, except the admin and this one
I don’t know if this is the most correct design practice with yii, but saved me a lot of coding.
All we have to do is to use 2 new prefixes for the 2 session types we need to use (public user and admin).
/Don’t use the default session prefix and only one new, because using
Yii::app()->user->logout(false);
will clear the both sessions, when called to clear only the default one/
Write a new controller in /protected/components/ and after that use it to extends the other controllers from /protected/controllers/ . In the init() method from the "base" controller set the new prefix like this:
so every time a controller is called the new session prefix is loaded (and only from one place)
For the admin is almost the same. Assuming the admin is a module we can use the class AdminModule which extends CWebModule and it’s located under protected/modules/admin. Then we can overwrite the beforeControllerAction method of the parent class in such a fashion:
public function beforeControllerAction($controller, $action)
{
if(parent::beforeControllerAction($controller, $action))
{
// this method is called before any module controller action is performed
// you may place customized code here
Yii::app()->user->setStateKeyPrefix(Yii::app()->user->getStateKeyPrefix()."__adm");
if($action->id !== "login" && Yii::app()->user->isGuest)
$controller->redirect(Yii::app()->params["URI_ADMIN"]."default/login/");
return true;
}
else
return false;
}
Finally to logout the proper user just set the $destroySession parameter to be false in the corresponding logout action: Yii::app()->user->logout(false);
Here is a topic which helps when some of the pages require login to be viewed: