Admin.php 14 KB

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