AuthRoleTrait.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. <?php
  2. namespace common\traits;
  3. use Yii;
  4. use yii\base\InvalidConfigException;
  5. use yii\data\ActiveDataProvider;
  6. use yii\web\UnprocessableEntityHttpException;
  7. use common\enums\StatusEnum;
  8. use common\enums\WhetherEnum;
  9. use common\helpers\ResultHelper;
  10. use common\models\rbac\AuthRole;
  11. use common\helpers\ArrayHelper;
  12. /**
  13. * Trait AuthRoleTrait
  14. * @package common\traits
  15. * @property \yii\db\ActiveRecord|\yii\base\Model $modelClass
  16. * @property string $appId 应用id
  17. * @property bool $sourceAuthChild 权限来源(false:所有权限,true:当前角色)
  18. * @property string $viewPrefix 加载视图
  19. * @author jianyan74 <751393839@qq.com>
  20. */
  21. trait AuthRoleTrait
  22. {
  23. /**
  24. * @throws InvalidConfigException
  25. */
  26. public function init()
  27. {
  28. parent::init();
  29. if ($this->modelClass === null) {
  30. throw new InvalidConfigException('"modelClass" 属性必须设置.');
  31. }
  32. if ($this->appId === null) {
  33. throw new InvalidConfigException('"appId" 属性必须设置.');
  34. }
  35. if ($this->sourceAuthChild === null) {
  36. throw new InvalidConfigException('"sourceAuthChild" 属性必须设置.');
  37. }
  38. if ($this->viewPrefix === null) {
  39. throw new InvalidConfigException('"viewPrefix" 属性必须设置.');
  40. }
  41. }
  42. /**
  43. * 首页
  44. *
  45. * @return mixed
  46. * @throws \yii\web\UnauthorizedHttpException
  47. */
  48. public function actionIndex()
  49. {
  50. $merchantId = Yii::$app->services->merchant->getNotNullId();
  51. $defaultRole = $this->getDefaultRole();
  52. $dataProvider = new ActiveDataProvider([
  53. 'query' => AuthRole::find()
  54. ->where(['app_id' => $this->appId])
  55. ->andWhere(['>=', 'status', StatusEnum::DISABLED])
  56. ->andFilterWhere(['merchant_id' => $merchantId])
  57. ->andFilterWhere(Yii::$app->services->rbacAuthRole->roleCondition($this->sourceAuthChild))
  58. ->orderBy('sort asc, created_at asc')
  59. ->asArray(),
  60. 'pagination' => false
  61. ]);
  62. $roles = $this->sourceAuthChild ? Yii::$app->services->rbacAuthRole->getRoles() : [];
  63. $models = $dataProvider->getModels();
  64. !empty($defaultRole) && $models[] = $defaultRole;
  65. !empty($defaultRole) && $roles[] = $defaultRole;
  66. $ids = ArrayHelper::getColumn($models, 'id');
  67. foreach ($models as &$model) {
  68. if (!in_array($model['pid'], $ids)) {
  69. $model['pid'] = 0;
  70. }
  71. }
  72. $dataProvider->setModels($models);
  73. return $this->render($this->viewPrefix . $this->action->id, [
  74. 'dataProvider' => $dataProvider,
  75. 'merchant_id' => $merchantId,
  76. 'roleIds' => ArrayHelper::getColumn($roles, 'id'),
  77. ]);
  78. }
  79. /**
  80. * @return array|mixed
  81. * @throws \yii\db\Exception
  82. * @throws \yii\web\UnauthorizedHttpException
  83. */
  84. public function actionEdit()
  85. {
  86. $id = Yii::$app->request->get('id', null);
  87. $merchantId = Yii::$app->services->merchant->getNotNullId();
  88. /** @var AuthRole $model */
  89. $model = $this->findModel($id);
  90. $model->pid = Yii::$app->request->get('pid', null) ?? $model->pid; // 父id
  91. $model->app_id = $this->appId;
  92. $defaultRole = $this->getDefaultRole();
  93. // 获取所有权限还是当前已有的权限
  94. if ($this->sourceAuthChild == true && !Yii::$app->services->rbacAuth->isSuperAdmin()) {
  95. $roles = Yii::$app->services->rbacAuthRole->findByLoginUser(Yii::$app->id);
  96. !empty($defaultRole) && $roles[$defaultRole['id']] = $defaultRole;
  97. if (!in_array($model->pid, array_keys($roles))) {
  98. throw new UnprocessableEntityHttpException('无权限操作当前角色');
  99. }
  100. $allAuth = Yii::$app->services->rbacAuthItemChild->findItemByRoleId($model->pid);
  101. } else {
  102. $allAuth = Yii::$app->services->rbacAuthItem->findAll($this->appId);
  103. }
  104. if (Yii::$app->request->isAjax) {
  105. $data = Yii::$app->request->post();
  106. $model->attributes = $data;
  107. $model->merchant_id = $merchantId ?? 0;
  108. if (!$model->save()) {
  109. return ResultHelper::json(422, $this->getError($model));
  110. }
  111. // 创建角色关联的权限信息
  112. Yii::$app->services->rbacAuthItemChild->accredit($model->id, $data['userTreeIds'] ?? [], WhetherEnum::DISABLED, $this->appId);
  113. Yii::$app->services->rbacAuthItemChild->accredit($model->id, $data['plugTreeIds'] ?? [], WhetherEnum::ENABLED, $this->appId);
  114. return ResultHelper::json(200, '提交成功');
  115. }
  116. list($defaultFormAuth, $defaultCheckIds, $addonsFormAuth, $addonsCheckIds) = Yii::$app->services->rbacAuthRole->getJsTreeData($id, $allAuth);
  117. $dropDownList = Yii::$app->services->rbacAuthRole->getDropDownForEdit($this->appId, $this->sourceAuthChild, '', !empty($defaultRole) ? [$defaultRole] : []);
  118. return $this->render($this->viewPrefix . $this->action->id, [
  119. 'model' => $model,
  120. 'defaultFormAuth' => $defaultFormAuth,
  121. 'defaultCheckIds' => $defaultCheckIds,
  122. 'addonsFormAuth' => $addonsFormAuth,
  123. 'addonsCheckIds' => $addonsCheckIds,
  124. 'dropDownList' => $dropDownList,
  125. 'merchant_id' => $merchantId
  126. ]);
  127. }
  128. /**
  129. * 删除
  130. *
  131. * @param $id
  132. * @return mixed
  133. * @throws \Throwable
  134. * @throws \yii\db\StaleObjectException
  135. */
  136. public function actionDelete($id)
  137. {
  138. if ($this->findModel($id)->delete()) {
  139. return $this->message("删除成功", $this->redirect(['index']));
  140. }
  141. return $this->message("删除失败", $this->redirect(['index']), 'error');
  142. }
  143. /**
  144. * ajax更新排序/状态
  145. *
  146. * @param $id
  147. * @return array
  148. */
  149. public function actionAjaxUpdate($id)
  150. {
  151. if (!($model = $this->modelClass::findOne($id))) {
  152. return ResultHelper::json(404, '找不到数据');
  153. }
  154. $model->attributes = ArrayHelper::filter(Yii::$app->request->get(), ['sort', 'status']);
  155. if (!$model->save()) {
  156. return ResultHelper::json(422, $this->getError($model));
  157. }
  158. return ResultHelper::json(200, '修改成功');
  159. }
  160. /**
  161. * 获取默认角色
  162. *
  163. * @return array
  164. */
  165. public function getDefaultRole()
  166. {
  167. return [];
  168. }
  169. /**
  170. * 返回模型
  171. *
  172. * @param $id
  173. * @return \yii\db\ActiveRecord
  174. */
  175. protected function findModel($id)
  176. {
  177. /* @var $model \yii\db\ActiveRecord */
  178. if (empty($id) || empty(($model = $this->modelClass::findOne($id)))) {
  179. $model = new $this->modelClass;
  180. return $model->loadDefaultValues();
  181. }
  182. return $model;
  183. }
  184. }
粤ICP备19079148号