Admin.php 12 KB

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