如何在YII2中显示每个用户在索引和视图中的角色?

时间:2015-08-20 11:20:14

标签: yii2

我的数据库中有所有RBAC表和一个用户表。 我设法在创建和更新用户时分配角色,它为每个user_id(角色)更新了item_name的auth_assignment表。

我的问题是 - 我想在我的user/index屏幕中添加另一列,它会告诉我每个用户的角色,以及user/view

到目前为止,我尝试的所有内容都无法正常工作,我尝试加入用户和auth_assignment表,但它没有帮助 - 它表示与auth_assignment无关。

代码:

models/User.php

<?php
namespace app\models;

use Yii;
use \yii\web\IdentityInterface;
use yii\helpers\ArrayHelper;
use app\models\Project;



/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $auth_key
 */
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    /**
     * @inheritdoc
     */

    public $role;

    public static function getRoles()
    {
            return ['admin'=>'admin','releaseManager'=>'releaseManager','pm'=>'pm','psw'=>'psw','qa'=>'qa'];
    }   

    public function afterSave($insert,$changedAttributes)
    {
            $return = parent::afterSave($insert,$changedAttributes);

            $auth = Yii::$app->authManager;
                $roleName = $this->role;
                $role = $auth->getRole($roleName);
                if (\Yii::$app->authManager->getRolesByUser($this->id) == null)
                {
                    $auth->assign($role, $this->id);
                }
                else
                {
                    $db = \Yii::$app->db;
                    $db->createCommand()->delete('auth_assignment',['user_id' => $this->id])->execute();
                    $auth->assign($role, $this->id);
                }

            return $return;
    }   

    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password', 'auth_key'], 'string', 'max' => 255],
            [['username', 'password','projectId','role'], 'required'],
            [['username'], 'unique']            
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'projectId' => 'Project Id',
            'auth_key' => 'Auth Key',
        /*  'role' => 'Role',*/
        ];
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('You can only login
                            by username/password pair for now.');
    }


    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validatePassword($password)
    {
        return $this->isCorrectHash($password, $this->password); 
    }
    private function isCorrectHash($plaintext, $hash)
    {
        return Yii::$app->security->validatePassword($plaintext, $hash);
    }
    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
         return $this->getAuthKey() === $authKey;
    }

    public function beforeSave($insert)
    {
        $return = parent::beforeSave($insert);

        if ($this->isAttributeChanged('password'))
            $this->password = Yii::$app->security->
                    generatePasswordHash($this->password);

        if ($this->isNewRecord)
            $this->auth_key = Yii::$app->security->generateRandomString(32);

        return $return;
    }

    public function getProject()
    {
        return $this->hasOne(Project::className(), ['id' => 'projectId']);
    }

    /*public function getRole()
    {
        return $this->hasOne(User::findByUsername($username)->getId() );
    }*/



    public static function getUsers()
    {
        if (\Yii::$app->user->can('assignUsersToPost'))
        {
            $users = ArrayHelper::
                map(self::find()->all(), 'id', 'username');
                //$users[null] = "All Users";
        } else {
            $users = ArrayHelper::
                map(self::find()->where(['id'=>Yii::$app->user->id])->all(), 'id', 'username');         
        }
        return $users;                      
    }
    public static function getCurrentUser()
    {
        $user = ArrayHelper::
                map(self::find()->where(['id'=>Yii::$app->user->id])->all(), 'id', 'username');         

        return $user;                       
    }
/*  public static function isSenderOrRciever($message)
    {
        $return = false;
        if (
            $message->fromUserId == Yii::$app->user->id
            || $message->toUserId == Yii::$app->user->id
        ) 
        $return = true; 
        return $return;
        }   */
}

UserController. php (创建和更新用户):

public function actionCreate()
    {
        $model = new User();
        $roles = User::getRoles();

        if (isset($_POST['User']['role']))
            $model->role = $_POST['User']['role'];


        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'roles' => $roles,
            ]);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $roles = User::getRoles();
        $model->password = null;

        $db = \Yii::$app->db;
        $command = $db->createCommand('SELECT * FROM auth_assignment WHERE user_id=:id');
        $command->bindValue(':id',$model->id);
        $assignment = $command->queryOne();
        $model->role = $assignment['item_name'];

        if (isset($_POST['User']['role']))
            $model->role = $_POST['User']['role'];

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'roles' => $roles,
            ]);
        }
    }
除了'views'之外,

_form个文件没有变化,因为我尝试的所有内容都会给我一个错误。 根据我的理解,我只需要在index.phpview.php文件中添加一个代码,以使其正常工作,但它已经过了1周,我仍然无法找到解决方案。

提前致谢, 珍妮

2 个答案:

答案 0 :(得分:2)

在GridView中,您始终可以创建一个包含函数的列,该函数可返回您需要的任何数据。因此,在列定义的索引视图中添加以下内容:

[
    'header' => 'Roles',
    'value' => function($data) {
        $roles = \Yii::$app->authManager->getRolesByUser($data->id);
        if ($roles) {
            return implode(', ', array_keys($roles));
        } else {
            return 'no roles';
        }
    }
],

正如您可以在文档中看到的那样,getRolesByUser会返回一个由角色名称索引的角色数组。这就是我们使用键来显示角色的原因。

如果您打算对该列进行过滤或排序,则必须实现正确的关系(在您的情况下为getRole())。否则,您只需使用authManager即可获得角色。

但是,这不适用于DetailView,因为您无法将函数传递给它。在这种情况下,您可以在模型中实现此功能:

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    //...
    getRoleAsText()
    {
        $roles = \Yii::$app->authManager->getRolesByUser($this->id);
        if ($roles) {
            return implode(', ', array_keys($roles));
        } else {
            return 'no roles';
        }
    }
    //...
}

之后,您可以在GridView和DetailsView中引用它:['label' => 'Role', 'value' => 'roleAsText']

答案 1 :(得分:1)

您可以使用以下函数返回索引roleName

的用户角色数组
$roleArr = Yii::$app->authManager->getRolesByUser($data->userid);