Admin.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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,16}')) {
  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,16}')) {
  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,12}|unique:admin,username,' . $row->id,
  176. 'email' => 'require|email|unique:admin,email,' . $row->id,
  177. 'password' => 'regex:\S{32}',
  178. ]);
  179. $result = $row->validate('Admin.edit')->save($params);
  180. if ($result === false) {
  181. exception($row->getError());
  182. }
  183. // 先移除所有权限
  184. model('AuthGroupAccess')->where('uid', $row->id)->delete();
  185. $group = $this->request->post("group/a");
  186. // 过滤不允许的组别,避免越权
  187. $group = array_intersect($this->childrenGroupIds, $group);
  188. if (!$group) {
  189. exception(__('The parent group exceeds permission limit'));
  190. }
  191. $dataset = [];
  192. foreach ($group as $value) {
  193. $dataset[] = ['uid' => $row->id, 'group_id' => $value];
  194. }
  195. model('AuthGroupAccess')->saveAll($dataset);
  196. Db::commit();
  197. } catch (\Exception $e) {
  198. Db::rollback();
  199. $this->error($e->getMessage());
  200. }
  201. $this->success();
  202. }
  203. $this->error(__('Parameter %s can not be empty', ''));
  204. }
  205. $grouplist = $this->auth->getGroups($row['id']);
  206. $groupids = [];
  207. foreach ($grouplist as $k => $v) {
  208. $groupids[] = $v['id'];
  209. }
  210. $this->view->assign("row", $row);
  211. $this->view->assign("groupids", $groupids);
  212. return $this->view->fetch();
  213. }
  214. /**
  215. * 删除
  216. */
  217. public function del($ids = "")
  218. {
  219. if (!$this->request->isPost()) {
  220. $this->error(__("Invalid parameters"));
  221. }
  222. $ids = $ids ? $ids : $this->request->post("ids");
  223. if ($ids) {
  224. $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
  225. // 避免越权删除管理员
  226. $childrenGroupIds = $this->childrenGroupIds;
  227. $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
  228. $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
  229. })->select();
  230. if ($adminList) {
  231. $deleteIds = [];
  232. foreach ($adminList as $k => $v) {
  233. $deleteIds[] = $v->id;
  234. }
  235. $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
  236. if ($deleteIds) {
  237. Db::startTrans();
  238. try {
  239. $this->model->destroy($deleteIds);
  240. model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
  241. Db::commit();
  242. } catch (\Exception $e) {
  243. Db::rollback();
  244. $this->error($e->getMessage());
  245. }
  246. $this->success();
  247. }
  248. $this->error(__('No rows were deleted'));
  249. }
  250. }
  251. $this->error(__('You have no permission'));
  252. }
  253. /**
  254. * 批量更新
  255. * @internal
  256. */
  257. public function multi($ids = "")
  258. {
  259. // 管理员禁止批量操作
  260. $this->error();
  261. }
  262. /**
  263. * 下拉搜索
  264. */
  265. public function selectpage()
  266. {
  267. $this->dataLimit = 'auth';
  268. $this->dataLimitField = 'id';
  269. return parent::selectpage();
  270. }
  271. }