Group.php 11 KB

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