我已经四处搜索,似乎无法找到问题的解决方案。我是新手开发者,如果这是直截了当的话,请道歉。
我希望根据用户角色进行简单的重定向。我有一个"角色"在我的"用户"中排表,我希望它们被引导到" 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));
}
有人知道怎么做吗?
非常感谢,我慢慢学习!
答案 0 :(得分:0)
为了实现角色基本访问,你必须省略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!';
}
您必须为用户管理数据库表,并且可能添加字段以存储用户角色常量。关于角色基本访问的进一步阅读是:
要继续阅读答案中提供的代码,请转到here。
为了执行您提到的重定向,请尝试:
// 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
文件夹中。