Group.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. * @param string|null $id
  114. * @return void
  115. * @throws Throwable
  116. */
  117. public function edit(string $id = null): void
  118. {
  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(true)
  161. ->where('id', 'in', $row->rules)
  162. ->select()->toArray();
  163. $rules = $row->rules ? explode(',', $row->rules) : [];
  164. foreach ($pidArr as $item) {
  165. $ruKey = array_search($item['pid'], $rules);
  166. if ($ruKey !== false) {
  167. unset($rules[$ruKey]);
  168. }
  169. }
  170. $row->rules = array_values($rules);
  171. $this->success('', [
  172. 'row' => $row
  173. ]);
  174. }
  175. /**
  176. * 删除
  177. * @param array $ids
  178. * @throws Throwable
  179. */
  180. public function del(array $ids = []): void
  181. {
  182. if (!$this->request->isDelete() || !$ids) {
  183. $this->error(__('Parameter error'));
  184. }
  185. $pk = $this->model->getPk();
  186. $data = $this->model->where($pk, 'in', $ids)->select();
  187. foreach ($data as $v) {
  188. $this->checkAuth($v->id);
  189. }
  190. $subData = $this->model->where('pid', 'in', $ids)->column('pid', 'id');
  191. foreach ($subData as $key => $subDatum) {
  192. if (!in_array($key, $ids)) {
  193. $this->error(__('Please delete the child element first, or use batch deletion'));
  194. }
  195. }
  196. $adminGroup = Db::name('admin_group_access')->where('uid', $this->auth->id)->column('group_id');
  197. $count = 0;
  198. $this->model->startTrans();
  199. try {
  200. foreach ($data as $v) {
  201. if (!in_array($v['id'], $adminGroup)) {
  202. $count += $v->delete();
  203. }
  204. }
  205. $this->model->commit();
  206. } catch (Throwable $e) {
  207. $this->model->rollback();
  208. $this->error($e->getMessage());
  209. }
  210. if ($count) {
  211. $this->success(__('Deleted successfully'));
  212. } else {
  213. $this->error(__('No rows were deleted'));
  214. }
  215. }
  216. /**
  217. * 远程下拉
  218. * @return void
  219. * @throws Throwable
  220. */
  221. public function select(): void
  222. {
  223. $data = $this->getGroups([['status', '=', 1]]);
  224. if ($this->assembleTree) {
  225. $data = $this->tree->assembleTree($this->tree->getTreeArray($data));
  226. }
  227. $this->success('', [
  228. 'options' => $data
  229. ]);
  230. }
  231. /**
  232. * 权限节点入库前处理
  233. * @throws Throwable
  234. */
  235. public function handleRules(array &$data): array
  236. {
  237. if (!empty($data['rules']) && is_array($data['rules'])) {
  238. $rules = AdminRule::select();
  239. $superAdmin = true;
  240. foreach ($rules as $rule) {
  241. if (!in_array($rule['id'], $data['rules'])) {
  242. $superAdmin = false;
  243. }
  244. }
  245. if ($superAdmin) {
  246. $data['rules'] = '*';
  247. } else {
  248. // 禁止添加`拥有自己全部权限`的分组
  249. if (!array_diff($this->auth->getRuleIds(), $data['rules'])) {
  250. $this->error(__('Role group has all your rights, please contact the upper administrator to add or do not need to add!'));
  251. }
  252. $data['rules'] = implode(',', $data['rules']);
  253. }
  254. } else {
  255. unset($data['rules']);
  256. }
  257. return $data;
  258. }
  259. /**
  260. * 获取分组
  261. * @param array $where
  262. * @return array
  263. * @throws Throwable
  264. */
  265. public function getGroups(array $where = []): array
  266. {
  267. $pk = $this->model->getPk();
  268. $initKey = $this->request->get("initKey/s", $pk);
  269. // 下拉选择时只获取:拥有所有权限并且有额外权限的分组
  270. $absoluteAuth = $this->request->get('absoluteAuth/b', false);
  271. if ($this->keyword) {
  272. $keyword = explode(' ', $this->keyword);
  273. foreach ($keyword as $item) {
  274. $where[] = [$this->quickSearchField, 'like', '%' . $item . '%'];
  275. }
  276. }
  277. if ($this->initValue) {
  278. $where[] = [$initKey, 'in', $this->initValue];
  279. }
  280. if (!$this->auth->isSuperAdmin()) {
  281. $authGroups = $this->auth->getAllAuthGroups($this->authMethod);
  282. if (!$absoluteAuth) $authGroups = array_merge($this->adminGroups, $authGroups);
  283. $where[] = ['id', 'in', $authGroups];
  284. }
  285. $data = $this->model->where($where)->select()->toArray();
  286. // 获取第一个权限的名称供列表显示-s
  287. foreach ($data as &$datum) {
  288. if ($datum['rules']) {
  289. if ($datum['rules'] == '*') {
  290. $datum['rules'] = __('Super administrator');
  291. } else {
  292. $rules = explode(',', $datum['rules']);
  293. if ($rules) {
  294. $rulesFirstTitle = AdminRule::where('id', $rules[0])->value('title');
  295. $datum['rules'] = count($rules) == 1 ? $rulesFirstTitle : $rulesFirstTitle . '等 ' . count($rules) . ' 项';
  296. }
  297. }
  298. } else {
  299. $datum['rules'] = __('No permission');
  300. }
  301. }
  302. // 获取第一个权限的名称供列表显示-e
  303. // 如果要求树状,此处先组装好 children
  304. return $this->assembleTree ? $this->tree->assembleChild($data) : $data;
  305. }
  306. /**
  307. * 检查权限
  308. * @param $groupId
  309. * @return void
  310. * @throws Throwable
  311. */
  312. public function checkAuth($groupId): void
  313. {
  314. $authGroups = $this->auth->getAllAuthGroups($this->authMethod);
  315. if (!$this->auth->isSuperAdmin() && !in_array($groupId, $authGroups)) {
  316. $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~'));
  317. }
  318. }
  319. }