Admin.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. namespace app\admin\controller\auth;
  3. use app\admin\model\AuthGroup;
  4. use app\admin\model\AuthGroupAccess;
  5. use app\common\controller\Backend;
  6. use fast\Random;
  7. use fast\Tree;
  8. use think\Db;
  9. use think\Validate;
  10. /**
  11. * 管理员管理
  12. *
  13. * @icon fa fa-users
  14. * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
  15. */
  16. class Admin extends Backend
  17. {
  18. /**
  19. * @var \app\admin\model\Admin
  20. */
  21. protected $model = null;
  22. protected $selectpageFields = 'id,username,nickname,avatar';
  23. protected $searchFields = 'id,username,nickname';
  24. protected $childrenGroupIds = [];
  25. protected $childrenAdminIds = [];
  26. public function _initialize()
  27. {
  28. parent::_initialize();
  29. $this->model = model('Admin');
  30. $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
  31. $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
  32. $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
  33. Tree::instance()->init($groupList);
  34. $groupdata = [];
  35. if ($this->auth->isSuperAdmin()) {
  36. $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
  37. foreach ($result as $k => $v) {
  38. $groupdata[$v['id']] = $v['name'];
  39. }
  40. } else {
  41. $result = [];
  42. $groups = $this->auth->getGroups();
  43. foreach ($groups as $m => $n) {
  44. $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
  45. $temp = [];
  46. foreach ($childlist as $k => $v) {
  47. $temp[$v['id']] = $v['name'];
  48. }
  49. $result[__($n['name'])] = $temp;
  50. }
  51. $groupdata = $result;
  52. }
  53. $this->view->assign('groupdata', $groupdata);
  54. $this->assignconfig("admin", ['id' => $this->auth->id]);
  55. }
  56. /**
  57. * 查看
  58. */
  59. public function index()
  60. {
  61. //设置过滤方法
  62. $this->request->filter(['strip_tags', 'trim']);
  63. if ($this->request->isAjax()) {
  64. //如果发送的来源是Selectpage,则转发到Selectpage
  65. if ($this->request->request('keyField')) {
  66. return $this->selectpage();
  67. }
  68. $childrenGroupIds = $this->childrenGroupIds;
  69. $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
  70. ->column('id,name');
  71. $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
  72. ->field('uid,group_id')
  73. ->select();
  74. $adminGroupName = [];
  75. foreach ($authGroupList as $k => $v) {
  76. if (isset($groupName[$v['group_id']])) {
  77. $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
  78. }
  79. }
  80. $groups = $this->auth->getGroups();
  81. foreach ($groups as $m => $n) {
  82. $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
  83. }
  84. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  85. $list = $this->model
  86. ->where($where)
  87. ->where('id', 'in', $this->childrenAdminIds)
  88. ->field(['password', 'salt', 'token'], true)
  89. ->order($sort, $order)
  90. ->paginate($limit);
  91. foreach ($list as $k => &$v) {
  92. $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
  93. $v['groups'] = implode(',', array_keys($groups));
  94. $v['groups_text'] = implode(',', array_values($groups));
  95. }
  96. unset($v);
  97. $result = array("total" => $list->total(), "rows" => $list->items());
  98. return json($result);
  99. }
  100. return $this->view->fetch();
  101. }
  102. /**
  103. * 添加
  104. */
  105. public function add()
  106. {
  107. if ($this->request->isPost()) {
  108. $this->token();
  109. $params = $this->request->post("row/a");
  110. if ($params) {
  111. Db::startTrans();
  112. try {
  113. if (!Validate::is($params['password'], '\S{6,30}')) {
  114. exception(__("Please input correct password"));
  115. }
  116. $params['salt'] = Random::alnum();
  117. $params['password'] = md5(md5($params['password']) . $params['salt']);
  118. $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
  119. $result = $this->model->validate('Admin.add')->save($params);
  120. if ($result === false) {
  121. exception($this->model->getError());
  122. }
  123. $group = $this->request->post("group/a");
  124. //过滤不允许的组别,避免越权
  125. $group = array_intersect($this->childrenGroupIds, $group);
  126. if (!$group) {
  127. exception(__('The parent group exceeds permission limit'));
  128. }
  129. $dataset = [];
  130. foreach ($group as $value) {
  131. $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
  132. }
  133. model('AuthGroupAccess')->saveAll($dataset);
  134. Db::commit();
  135. } catch (\Exception $e) {
  136. Db::rollback();
  137. $this->error($e->getMessage());
  138. }
  139. $this->success();
  140. }
  141. $this->error(__('Parameter %s can not be empty', ''));
  142. }
  143. return $this->view->fetch();
  144. }
  145. /**
  146. * 编辑
  147. */
  148. public function edit($ids = null)
  149. {
  150. $row = $this->model->get(['id' => $ids]);
  151. if (!$row) {
  152. $this->error(__('No Results were found'));
  153. }
  154. if (!in_array($row->id, $this->childrenAdminIds)) {
  155. $this->error(__('You have no permission'));
  156. }
  157. if ($this->request->isPost()) {
  158. $this->token();
  159. $params = $this->request->post("row/a");
  160. if ($params) {
  161. Db::startTrans();
  162. try {
  163. if ($params['password']) {
  164. if (!Validate::is($params['password'], '\S{6,30}')) {
  165. exception(__("Please input correct password"));
  166. }
  167. $params['salt'] = Random::alnum();
  168. $params['password'] = md5(md5($params['password']) . $params['salt']);
  169. } else {
  170. unset($params['password'], $params['salt']);
  171. }
  172. //这里需要针对username和email做唯一验证
  173. $adminValidate = \think\Loader::validate('Admin');
  174. $adminValidate->rule([
  175. 'username' => 'require|regex:\w{3,30}|unique:admin,username,' . $row->id,
  176. 'email' => 'require|email|unique:admin,email,' . $row->id,
  177. 'mobile' => 'regex:1[3-9]\d{9}|unique:admin,mobile,' . $row->id,
  178. 'password' => 'regex:\S{32}',
  179. ]);
  180. $result = $row->validate('Admin.edit')->save($params);
  181. if ($result === false) {
  182. exception($row->getError());
  183. }
  184. // 先移除所有权限
  185. model('AuthGroupAccess')->where('uid', $row->id)->delete();
  186. $group = $this->request->post("group/a");
  187. // 过滤不允许的组别,避免越权
  188. $group = array_intersect($this->childrenGroupIds, $group);
  189. if (!$group) {
  190. exception(__('The parent group exceeds permission limit'));
  191. }
  192. $dataset = [];
  193. foreach ($group as $value) {
  194. $dataset[] = ['uid' => $row->id, 'group_id' => $value];
  195. }
  196. model('AuthGroupAccess')->saveAll($dataset);
  197. Db::commit();
  198. } catch (\Exception $e) {
  199. Db::rollback();
  200. $this->error($e->getMessage());
  201. }
  202. $this->success();
  203. }
  204. $this->error(__('Parameter %s can not be empty', ''));
  205. }
  206. $grouplist = $this->auth->getGroups($row['id']);
  207. $groupids = [];
  208. foreach ($grouplist as $k => $v) {
  209. $groupids[] = $v['id'];
  210. }
  211. $this->view->assign("row", $row);
  212. $this->view->assign("groupids", $groupids);
  213. return $this->view->fetch();
  214. }
  215. /**
  216. * 删除
  217. */
  218. public function del($ids = "")
  219. {
  220. if (!$this->request->isPost()) {
  221. $this->error(__("Invalid parameters"));
  222. }
  223. $ids = $ids ? $ids : $this->request->post("ids");
  224. if ($ids) {
  225. $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
  226. // 避免越权删除管理员
  227. $childrenGroupIds = $this->childrenGroupIds;
  228. $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
  229. $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
  230. })->select();
  231. if ($adminList) {
  232. $deleteIds = [];
  233. foreach ($adminList as $k => $v) {
  234. $deleteIds[] = $v->id;
  235. }
  236. $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
  237. if ($deleteIds) {
  238. Db::startTrans();
  239. try {
  240. $this->model->destroy($deleteIds);
  241. model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
  242. Db::commit();
  243. } catch (\Exception $e) {
  244. Db::rollback();
  245. $this->error($e->getMessage());
  246. }
  247. $this->success();
  248. }
  249. $this->error(__('No rows were deleted'));
  250. }
  251. }
  252. $this->error(__('You have no permission'));
  253. }
  254. /**
  255. * 批量更新
  256. * @internal
  257. */
  258. public function multi($ids = "")
  259. {
  260. // 管理员禁止批量操作
  261. $this->error();
  262. }
  263. /**
  264. * 下拉搜索
  265. */
  266. public function selectpage()
  267. {
  268. $this->dataLimit = 'auth';
  269. $this->dataLimitField = 'id';
  270. return parent::selectpage();
  271. }
  272. }