[英]Yii 1.1 Login redirect depending on user role (Role based access control)
我四處搜尋,似乎找不到解決問題的方法。 我是菜鳥開發者,如果這很簡單,請您道歉。
我想根據用戶角色進行簡單的重定向。 我的“用戶”表中有一個“角色”行,如果它們是“用戶”,我希望將它們定向到“ Index.php”頁面,如果它們是“管理員”,則希望將它們定向到“儀表盤”頁面。
我知道這與“ SiteController”有關,但我不確定確切的代碼。 作為參考,我目前在“ ActionLogin”功能下有以下內容-
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// 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())
$this->redirect(array("Site/Dashboard"));
}
// display the login form
$this->render('login',array('model'=>$model));
}
有人知道怎么做這個嗎?
非常感謝,我正在慢慢學習!
為了實現基於角色的訪問,您必須使用Yii的默認實現,該默認實現僅與用戶身份驗證(用戶已登錄或用戶為訪客)一起提供。
為了從基於角色的訪問開始,我建議您首先通過擴展Yii CWebUser類來實現用戶類。
就像是:
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;
}
}
如您所見, User::LEVEL_SUPERADMIN
和User::LEVEL_ADMIN
由CWebUser提供。 然后在您的站點控制器中accessRules()放置類似以下內容:
// 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('*').
),
);
}
為了將新類與基於角色的訪問一起使用,請將其作為應用程序組件添加到config / main.php文件中:
'components'=>array(
'user'=>array(
//tell the application to use your WebUser class
'class'=>'WebUser'
),
),
在您的視圖中,可以使用以下命令查看其工作方式:
if(Yii::app()->user->isAdmin){
echo 'Administrator!';
}
if(Yii::app()->user->isSuperAdmin){
echo 'SuperAdmin!';
}
您必須為用戶管理數據庫表,並可能添加字段以存儲用戶角色常量。 有關“角色庫訪問”的更多信息是:
要繼續閱讀答案中提供的代碼,請轉到此處 。
為了執行您提到的重定向,請嘗試:
// 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));
}
請注意 , dashboard.php文件必須放在/protected/views/site
文件夾中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.