AuthAssignmentService.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace services\rbac;
  3. use Yii;
  4. use yii\web\UnprocessableEntityHttpException;
  5. use common\helpers\ArrayHelper;
  6. use common\components\Service;
  7. use common\models\rbac\AuthAssignment;
  8. /**
  9. *
  10. * 授权角色
  11. *
  12. * Class AuthAssignmentService
  13. * @package services\rbac
  14. * @author qimall
  15. */
  16. class AuthAssignmentService extends Service
  17. {
  18. /**
  19. * 分配角色
  20. *
  21. * @param array $role_ids 角色id
  22. * @param int $user_id 用户id
  23. * @param string $app_id 应用id
  24. * @throws UnprocessableEntityHttpException
  25. */
  26. public function assign(array $role_ids, int $user_id, string $app_id)
  27. {
  28. // 移除已有的授权
  29. AuthAssignment::deleteAll(['user_id' => $user_id, 'app_id' => $app_id]);
  30. foreach ($role_ids as $role_id) {
  31. $model = new AuthAssignment();
  32. $model->user_id = $user_id;
  33. $model->role_id = $role_id;
  34. $model->app_id = $app_id;
  35. if (!$model->save()) {
  36. throw new UnprocessableEntityHttpException($this->getError($model));
  37. }
  38. }
  39. }
  40. /**
  41. * 获取当前用户权限的下面的所有用户id
  42. *
  43. * @param $app_id
  44. * @return array
  45. * @throws \yii\web\UnauthorizedHttpException
  46. */
  47. public function getChildIds($app_id)
  48. {
  49. if (Yii::$app->services->auth->isSuperAdmin()) {
  50. return [];
  51. }
  52. $childRoles = Yii::$app->services->rbacAuthRole->getChildes($app_id);
  53. $childRoleIds = ArrayHelper::getColumn($childRoles, 'id');
  54. if (!$childRoleIds) {
  55. return [-1];
  56. }
  57. $userIds = AuthAssignment::find()
  58. ->where(['app_id' => $app_id])
  59. ->andWhere(['in', 'role_id', $childRoleIds])
  60. ->select('user_id')
  61. ->asArray()
  62. ->column();
  63. return !empty($userIds) ? $userIds : [-1];
  64. }
  65. /**
  66. * @param $user_id
  67. * @param $app_id
  68. * @return array|\yii\db\ActiveRecord|null
  69. */
  70. public function findByUserIdAndAppId($user_id, $app_id)
  71. {
  72. return AuthAssignment::find()
  73. ->where(['app_id' => $app_id])
  74. ->andWhere(['user_id' => $user_id])
  75. ->asArray()
  76. ->one();
  77. }
  78. }