Group.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <?php
  2. namespace app\admin\controller\auth;
  3. use ba\Tree;
  4. use Throwable;
  5. use think\facade\Db;
  6. use app\admin\model\AdminRule;
  7. use app\admin\model\AdminGroup;
  8. use app\common\controller\Backend;
  9. class Group extends Backend
  10. {
  11. /**
  12. * 修改、删除分组时对操作管理员进行鉴权
  13. * 本管理功能部分场景对数据权限有要求,修改此值请额外确定以下的 absoluteAuth 实现的功能
  14. * allAuthAndOthers=管理员拥有该分组所有权限并拥有额外权限时允许
  15. */
  16. protected string $authMethod = 'allAuthAndOthers';
  17. /**
  18. * 数据模型
  19. * @var object
  20. * @phpstan-var AdminGroup
  21. */
  22. protected object $model;
  23. protected string|array $preExcludeFields = ['create_time', 'update_time'];
  24. protected string|array $quickSearchField = 'name';
  25. /**
  26. * @var Tree
  27. */
  28. protected Tree $tree;
  29. /**
  30. * 远程select初始化传值
  31. * @var array
  32. */
  33. protected array $initValue;
  34. /**
  35. * 搜索关键词
  36. * @var string
  37. */
  38. protected string $keyword;
  39. /**
  40. * 是否组装Tree
  41. * @var bool
  42. */
  43. protected bool $assembleTree;
  44. /**
  45. * 登录管理员的角色组
  46. * @var array
  47. */
  48. protected array $adminGroups = [];
  49. public function initialize(): void
  50. {
  51. parent::initialize();
  52. $this->model = new AdminGroup();
  53. $this->tree = Tree::instance();
  54. $isTree = $this->request->param('isTree', true);
  55. $this->initValue = $this->request->get("initValue/a", []);
  56. $this->initValue = array_filter($this->initValue);
  57. $this->keyword = $this->request->request("quickSearch", '');
  58. // 有初始化值时不组装树状(初始化出来的值更好看)
  59. $this->assembleTree = $isTree && !$this->initValue;
  60. $this->adminGroups = Db::name('admin_group_access')->where('uid', $this->auth->id)->column('group_id');
  61. }
  62. public function index(): void
  63. {
  64. if ($this->request->param('select')) {
  65. $this->select();
  66. }
  67. $this->success('', [
  68. 'list' => $this->getGroups(),
  69. 'group' => $this->adminGroups,
  70. 'remark' => get_route_remark(),
  71. ]);
  72. }
  73. /**
  74. * 添加
  75. * @throws Throwable
  76. */
  77. public function add(): void
  78. {
  79. if ($this->request->isPost()) {
  80. $data = $this->request->post();
  81. if (!$data) {
  82. $this->error(__('Parameter %s can not be empty', ['']));
  83. }
  84. $data = $this->excludeFields($data);
  85. $data = $this->handleRules($data);
  86. $result = false;
  87. $this->model->startTrans();
  88. try {
  89. // 模型验证
  90. if ($this->modelValidate) {
  91. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  92. if (class_exists($validate)) {
  93. $validate = new $validate();
  94. $validate->scene('add')->check($data);
  95. }
  96. }
  97. $result = $this->model->save($data);
  98. $this->model->commit();
  99. } catch (Throwable $e) {
  100. $this->model->rollback();
  101. $this->error($e->getMessage());
  102. }
  103. if ($result !== false) {
  104. $this->success(__('Added successfully'));
  105. } else {
  106. $this->error(__('No rows were added'));
  107. }
  108. }
  109. $this->error(__('Parameter error'));
  110. }
  111. /**
  112. * 编辑
  113. * @throws Throwable
  114. */
  115. public function edit(): void
  116. {
  117. $pk = $this->model->getPk();
  118. $id = $this->request->param($pk);
  119. $row = $this->model->find($id);
  120. if (!$row) {
  121. $this->error(__('Record not found'));
  122. }
  123. $this->checkAuth($id);
  124. if ($this->request->isPost()) {
  125. $data = $this->request->post();
  126. if (!$data) {
  127. $this->error(__('Parameter %s can not be empty', ['']));
  128. }
  129. $adminGroup = Db::name('admin_group_access')->where('uid', $this->auth->id)->column('group_id');
  130. if (in_array($data['id'], $adminGroup)) {
  131. $this->error(__('You cannot modify your own management group!'));
  132. }
  133. $data = $this->excludeFields($data);
  134. $data = $this->handleRules($data);
  135. $result = false;
  136. $this->model->startTrans();
  137. try {
  138. // 模型验证
  139. if ($this->modelValidate) {
  140. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  141. if (class_exists($validate)) {
  142. $validate = new $validate();
  143. $validate->scene('edit')->check($data);
  144. }
  145. }
  146. $result = $row->save($data);
  147. $this->model->commit();
  148. } catch (Throwable $e) {
  149. $this->model->rollback();
  150. $this->error($e->getMessage());
  151. }
  152. if ($result !== false) {
  153. $this->success(__('Update successful'));
  154. } else {
  155. $this->error(__('No rows updated'));
  156. }
  157. }
  158. // 读取所有pid,全部从节点数组移除,父级选择状态由子级决定
  159. $pidArr = AdminRule::field('pid')
  160. ->distinct()
  161. ->where('id', 'in', $row->rules)
  162. ->select()
  163. ->toArray();
  164. $rules = $row->rules ? explode(',', $row->rules) : [];
  165. foreach ($pidArr as $item) {
  166. $ruKey = array_search($item['pid'], $rules);
  167. if ($ruKey !== false) {
  168. unset($rules[$ruKey]);
  169. }
  170. }
  171. $row->rules = array_values($rules);
  172. $this->success('', [
  173. 'row' => $row
  174. ]);
  175. }
  176. /**
  177. * 删除
  178. * @throws Throwable
  179. */
  180. public function del(): void
  181. {
  182. $ids = $this->request->param('ids/a', []);
  183. $data = $this->model->where($this->model->getPk(), 'in', $ids)->select();
  184. foreach ($data as $v) {
  185. $this->checkAuth($v->id);
  186. }
  187. $subData = $this->model->where('pid', 'in', $ids)->column('pid', 'id');
  188. foreach ($subData as $key => $subDatum) {
  189. if (!in_array($key, $ids)) {
  190. $this->error(__('Please delete the child element first, or use batch deletion'));
  191. }
  192. }
  193. $adminGroup = Db::name('admin_group_access')->where('uid', $this->auth->id)->column('group_id');
  194. $count = 0;
  195. $this->model->startTrans();
  196. try {
  197. foreach ($data as $v) {
  198. if (!in_array($v['id'], $adminGroup)) {
  199. $count += $v->delete();
  200. }
  201. }
  202. $this->model->commit();
  203. } catch (Throwable $e) {
  204. $this->model->rollback();
  205. $this->error($e->getMessage());
  206. }
  207. if ($count) {
  208. $this->success(__('Deleted successfully'));
  209. } else {
  210. $this->error(__('No rows were deleted'));
  211. }
  212. }
  213. /**
  214. * 远程下拉
  215. * @return void
  216. * @throws Throwable
  217. */
  218. public function select(): void
  219. {
  220. $data = $this->getGroups([['status', '=', 1]]);
  221. if ($this->assembleTree) {
  222. $data = $this->tree->assembleTree($this->tree->getTreeArray($data));
  223. }
  224. $this->success('', [
  225. 'options' => $data
  226. ]);
  227. }
  228. /**
  229. * 权限节点入库前处理
  230. * @throws Throwable
  231. */
  232. private function handleRules(array &$data): array
  233. {
  234. if (!empty($data['rules']) && is_array($data['rules'])) {
  235. $superAdmin = true;
  236. $checkedRules = [];
  237. $allRuleIds = AdminRule::column('id');
  238. // 遍历检查权限ID是否存在(以免传递了可预测的未来权限ID号)
  239. foreach ($data['rules'] as $postRuleId) {
  240. if (in_array($postRuleId, $allRuleIds)) {
  241. $checkedRules[] = $postRuleId;
  242. }
  243. }
  244. // 正在建立超管级分组?
  245. foreach ($allRuleIds as $ruleId) {
  246. if (!in_array($ruleId, $checkedRules)) {
  247. $superAdmin = false;
  248. }
  249. }
  250. if ($superAdmin && $this->auth->isSuperAdmin()) {
  251. // 允许超管建立超管级分组
  252. $data['rules'] = '*';
  253. } else {
  254. // 当前管理员所拥有的权限节点
  255. $ownedRuleIds = $this->auth->getRuleIds();
  256. // 禁止添加`拥有自己全部权限`的分组
  257. if (!array_diff($ownedRuleIds, $checkedRules)) {
  258. $this->error(__('Role group has all your rights, please contact the upper administrator to add or do not need to add!'));
  259. }
  260. // 检查分组权限是否超出了自己的权限(超管的 $ownedRuleIds 为 ['*'],不便且可以不做此项检查)
  261. if (array_diff($checkedRules, $ownedRuleIds) && !$this->auth->isSuperAdmin()) {
  262. $this->error(__('The group permission node exceeds the range that can be allocated'));
  263. }
  264. $data['rules'] = implode(',', $checkedRules);
  265. }
  266. } else {
  267. unset($data['rules']);
  268. }
  269. return $data;
  270. }
  271. /**
  272. * 获取分组
  273. * @param array $where
  274. * @return array
  275. * @throws Throwable
  276. */
  277. private function getGroups(array $where = []): array
  278. {
  279. $pk = $this->model->getPk();
  280. $initKey = $this->request->get("initKey/s", $pk);
  281. // 下拉选择时只获取:拥有所有权限并且有额外权限的分组
  282. $absoluteAuth = $this->request->get('absoluteAuth/b', false);
  283. if ($this->keyword) {
  284. $keyword = explode(' ', $this->keyword);
  285. foreach ($keyword as $item) {
  286. $where[] = [$this->quickSearchField, 'like', '%' . $item . '%'];
  287. }
  288. }
  289. if ($this->initValue) {
  290. $where[] = [$initKey, 'in', $this->initValue];
  291. }
  292. if (!$this->auth->isSuperAdmin()) {
  293. $authGroups = $this->auth->getAllAuthGroups($this->authMethod, $where);
  294. if (!$absoluteAuth) $authGroups = array_merge($this->adminGroups, $authGroups);
  295. $where[] = ['id', 'in', $authGroups];
  296. }
  297. $data = $this->model->where($where)->select()->toArray();
  298. // 获取第一个权限的名称供列表显示-s
  299. foreach ($data as &$datum) {
  300. if ($datum['rules']) {
  301. if ($datum['rules'] == '*') {
  302. $datum['rules'] = __('Super administrator');
  303. } else {
  304. $rules = explode(',', $datum['rules']);
  305. if ($rules) {
  306. $rulesFirstTitle = AdminRule::where('id', $rules[0])->value('title');
  307. $datum['rules'] = count($rules) == 1 ? $rulesFirstTitle : $rulesFirstTitle . '等 ' . count($rules) . ' 项';
  308. }
  309. }
  310. } else {
  311. $datum['rules'] = __('No permission');
  312. }
  313. }
  314. // 获取第一个权限的名称供列表显示-e
  315. // 如果要求树状,此处先组装好 children
  316. return $this->assembleTree ? $this->tree->assembleChild($data) : $data;
  317. }
  318. /**
  319. * 检查权限
  320. * @param $groupId
  321. * @return void
  322. * @throws Throwable
  323. */
  324. private function checkAuth($groupId): void
  325. {
  326. $authGroups = $this->auth->getAllAuthGroups($this->authMethod, []);
  327. if (!$this->auth->isSuperAdmin() && !in_array($groupId, $authGroups)) {
  328. $this->error(__($this->authMethod == 'allAuth' ? 'You need to have all permissions of this group to operate this group~' : 'You need to have all the permissions of the group and have additional permissions before you can operate the group~'));
  329. }
  330. }
  331. }