繁体   English   中英

Yii:获取登录用户的角色并根据角色显示内容

[英]Yii: Getting the role of logged in users and showing content according to role

我希望获得注册用户的角色,并根据他们的角色向注册用户显示内容。 我现在有两个用户。

  1. 管理
  2. 用户(认证)

我想要做的是,当管理员通过“ webapp / user / login登录时 ,我已经制作的sidebarwidget应该在登录时显示,当用户(经过身份验证)登录时,用户(已验证)应该只能看到index.php页面。

我正在使用Yii用户权利 我环顾四周,发现这段代码用于获取登录用户的角色,但我不知道在哪里放置这段代码来获取输出。 以下是两段代码,请告诉我哪一段更有用。

 if($user = Users::model()->findAll()) {
    foreach($user as $id => $user) {
    if(!$user->checkAccess('Authenticated')) {
        unset($user[$id]);
        }
    }
    $users = array_values($user); // to reset indices (optional)
}

这是我发现的另一段代码。

$command = Yii::app()->db->createCommand("SELECT * FROM `authassignment` WHERE userid={$user->id}");
$results = $command->queryAll();
$roles = array();
foreach ($results as $result)
{
  $roles[] = $result['itemname'];
}
$this->setState('roles', $roles);

根据我在教程后所做的工作,这是一个提案。

身份验证可以在文件protected / components / UserIdentity.php中进行:

public function authenticate($native=false){
    $record=User::model()->findByAttributes(array('username'=>$this->username));
    //can provide function "same" if needed - found it here:
    //http://codereview.stackexchange.com/questions/13512
    if($record!==null&&$this->same($record->password,crypt($this->password,$record->password)){
        $authRoleName=Role::model()->findByAttributes(array('id'=>$record->role_id))->name;
        $this->setState('role_name', $authRoleName);
        $this->errorCode = self::ERROR_NONE;
    }else{
        $this->errorCode=self::ERROR_UNKNOWN_IDENTITY;
    }
    return !$this->errorCode;
}

在这种情况下,几个角色(管理员,移动设备,用户等)存储在db(表角色)中,每个用户模型都有一个role_id。

我假设SiteController执行登录(文件protected / controllers / SiteController.php):

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(Yii::app()->user->returnUrl);
        }
    }
    // display the login form
    $this->render('login',array('model'=>$model));
}

文件保护/ models / LoginForm.php:

class LoginForm extends CFormModel
public $username;
public $password;
public $rememberMe;

private $_identity;

public function authenticate($attribute,$params)
{
    if(!$this->hasErrors())
    {
        $this->_identity=new UserIdentity($this->username,$this->password);
        if(!$this->_identity->authenticate())
            $this->addError('password','False username or password.');
    }
}

public function login()
{
    if($this->_identity===null)
    {
        $this->_identity=new UserIdentity($this->username,$this->password);
        $this->_identity->authenticate();
    }
    if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
    {
        $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
        Yii::app()->user->login($this->_identity, duration);
        return true;
    }
    else
        return false;
}

在视图中,您可以执行基于角色的决策制定,如下面的文件protected / views / site / index.php中的示例:

<?php
$userModel =User::model()->findByAttributes(array('id'=>Yii::app()->user->getId()));
if($userModel){
    if(Yii::app()->user->getState('role_name') == 'admin'){
        $this->renderPartial(
        //...
        );
     }else{
         //...
     }
}    

此外,如果你想到RBAC,并且你设法有一个适当的protected / data / auth.php(有办法,我在创建文件protected / commands / RbacCommand后使用命令“./protected/yiic rbac”。 php - 如果需要,我可以发布后一个文件)然后在你的代码中的任何地方你只需:

if(Yii::app()->user->checkAccess('admin')){
    //staff for admins
}

此外,在这种情况下,您可以通过发出角色而不是用户名来设置控制器函数accessRules()中的整个操作的权限:

public function accessRules()
{
    return array{
        array('allow',
            'actions'=>array('index', 'index2', 'view','create','update','getRecordDetails', 'getTotalCount'),
            'roles'=>array('admin'),
        ),
    );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM