Yii2:更新用户权限

时间:2018-03-23 11:02:47

标签: php yii2

我试图更新用户,包括他的权限。这就是我这样做的方式。似乎我错过了一些东西,但我不知道它到底是什么。

public function actionUpdate($id)
{
$model = $this->findModel($id);
$perfis = $model->authAssignment;

foreach ($perfis as $perfil) {
  array_push($model->perfil_array, $perfil->item_name);
}

if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  $itemsSaved = false;
  $permissionsList = Yii::$app->request->post()['User']['perfil_array'];
  if (!empty($permissionsList)) {
      foreach ($permissionsList as $permission) {
         $newPermission = new AuthAssignment;
         $newPermission->item_name = $permission;
         $newPermission->user_id = $id;
         if($newPermission->save()){
            print_r("ok");
         } else {
            print_r($newPermission->getErrors()); die;
         }
      }
   }
   if ($model->save()) {
      $itemsSaved = true;
   } else {
     print_r($model->getErrors());die;
     return $this->render('update', [
     'model' => $model,]);
   }
   if ($itemsSaved) {
      return $this->redirect(['view', 'id' => $model->id]);
   }
}
return $this->render('update', ['model' => $model,]);
}

我从表单复选框中获取所有已发布的权限,并将其保存到AuthAssignment表,但它会抛出此错误。

Array
(
    [item_name] => Array
        (
            [0] => The combination "Admin"-"10" of Item Name and User ID has already been taken.
        )

    [user_id] => Array
        (
            [0] => The combination "Admin"-"10" of Item Name and User ID has already been taken.
        )

)

用户模型:

class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    public $currentPassword;
    public $newPassword;
    public $newPasswordConfirm;
    public $perfil;
    public $perfil_array = [];

    public function attributeLabels()
    {
        return [
            'currentPassword' => 'Palavra passe atual',
            'newPassword' => 'Nova palavra passe',
            'newPasswordConfirm' => 'Confirmar nova palavra passse',
            'created_at' =>  'Data Criação',
            'updated_at' =>  'Data Atualização',
        ];
    }
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],                
        ];
    }
    public function getAuthAssignment() {
        return $this->hasMany(AuthAssignment::className(), ['user_id' => 'id']);
    }

如何在更新前删除用户的所有权限?

2 个答案:

答案 0 :(得分:1)

您可以尝试检查条目是否存在,一种方法是检查用户是否已拥有该权限。

if (!empty($permissionsList)) {

    // Get the authentication component
    $auth = Yii::$app->authManager;

    foreach ($permissionsList as $permission) {

        // Check if the user has the permission
        if (!$auth->checkAccess($id, $permission)) {

            // Check if the permission exists
            if ($auth->getPermission($permission) !== null) {

                // Create the new permission and add it to the rbac system
                $newPermission = $auth->createPermission($permission);
                $newPermission->description = 'my cool description';                      
                $auth->add($newPermission);

            }             

            /* 
             * Once here we know that the permission exists, it 
             * was there before or we created it.
             * I am going to assume that the user exists.
             * We can go ahead and give that user the permission.
             */
            try {
                $auth->assign($newPermission, $id);
            } catch (Exception $e) {
                Yii::error($e, __METHOD__);
            }
        }
    }
}

答案 1 :(得分:0)

这是经过一些研究后成功完成的。

if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    $itemsSaved = false;
    $permissionsList = Yii::$app->request->post()['User']['perfil_array'];
    if (!empty($permissionsList)) {
        $permissions = AuthAssignment::find()
        ->where(['user_id' => $id])->all();
        if (!empty($permissions)) {
            foreach ($permissions as $permission) {
                $permission->delete();
            }
        }
        foreach ($permissionsList as $permission) {
            $newPermission = new AuthAssignment;
            if ($newPermission->item_name != $permission) {
                $newPermission->item_name = $permission;
                $newPermission->user_id = $id;
            }
            if($newPermission->save()){
                print_r("okkkkkkkkk");
            } else {
                print_r($newPermission->getErrors());
            }
        } 
  }
  if ($model->save()) {
      $itemsSaved = true;
  } else {
      print_r($model->getErrors());die;
      return $this->render('update', [
      'model' => $model,]);
  }
  if ($itemsSaved) {
      return $this->redirect(['view', 'id' => $model->id]);
  }


}

我找到该特定用户的所有权限,并在分配新权限之前删除所有权限。不知道这是否是最佳方式,但它有效。