Admin.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. namespace app\admin\controller;
  3. use app\BaseController;
  4. use app\admin\model\Admin as AdminModel;
  5. use app\admin\model\RoleMenu;
  6. use app\admin\model\Menu;
  7. use think\exception\Exception;
  8. use think\facade\Db;
  9. use app\admin\validate\AdminValidate;
  10. use app\admin\model\User;
  11. use app\admin\model\KefuWork;
  12. use think\facade\Session;
  13. use app\admin\model\KefuTime;
  14. use thans\jwt\facade\JWTAuth;
  15. class Admin extends BaseController
  16. {
  17. protected $noNeedLogin = ['login'];
  18. /**
  19. * @api {get} /list 查询管理员列表
  20. */
  21. public function list()
  22. {
  23. try {
  24. $params = $this->request->param();
  25. $query = new AdminModel();
  26. if (!empty($params['username'])) {
  27. $query->where('username', 'like', "%{$params['username']}%");
  28. }
  29. if (!empty($params['phone'])) {
  30. $query->where('phone', 'like', "%{$params['phone']}%");
  31. }
  32. $page = isset($params['page']) ? intval($params['page']) : 1;
  33. $limit = isset($params['limit']) ? intval($params['limit']) : 15;
  34. $count = $query->count();
  35. $list = $query->with(['role', 'department'])
  36. ->order('id', 'desc')
  37. ->limit($limit)
  38. ->page($page)
  39. ->select();
  40. } catch (\Exception $e) {
  41. return $this->error('查询失败:'.$e->getMessage());
  42. }
  43. return $this->success(['count' => $count, 'list' => $list]);
  44. }
  45. /**
  46. * @api {post} /update 添加/修改管理员
  47. */
  48. public function update()
  49. {
  50. Db::startTrans();
  51. try {
  52. $params = (new AdminValidate())->post()->goCheck('add');
  53. $id = $this->request->param('id');
  54. // 只允许超级管理员配置
  55. if ($this->admin_id != 1) {
  56. return $this->error('只有超级管理员才能操作');
  57. }
  58. if (empty($id)) {
  59. // 新增校验
  60. if (empty($params['password'])) {
  61. return $this->error('密码不能为空');
  62. }
  63. if (empty($params['role_id'])) {
  64. return $this->error('角色ID不能为空');
  65. }
  66. if (empty($params['department_id'])) {
  67. return $this->error('部门ID不能为空');
  68. }
  69. } elseif ($id != 1) {
  70. if (empty($params['role_id'])) {
  71. return $this->error('角色ID不能为空');
  72. }
  73. if (empty($params['department_id'])) {
  74. return $this->error('部门ID不能为空');
  75. }
  76. }
  77. if (!empty($params['password'])) {
  78. $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
  79. } else {
  80. unset($params['password']);
  81. }
  82. if (!empty($params['payment_password'])) {
  83. $params['payment_password'] = password_hash($params['payment_password'], PASSWORD_DEFAULT);
  84. } else {
  85. unset($params['payment_password']);
  86. }
  87. $usernameCount = AdminModel::where('username', $params['username'])
  88. ->where('id', '<>', $id ?? 0)
  89. ->count();
  90. if ($usernameCount > 0) {
  91. return $this->error('用户名已存在');
  92. }
  93. $role = AdminModel::getRole($params['role_id']);
  94. if (!empty($id)) {
  95. unset($params['username']);
  96. AdminModel::where('id', $id)->update($params);
  97. User::where('uid', $id)->where('from', 0)->update(['role' => $role, 'realname' => $params['nickname'], 'phone' => $params['phone'], 'remark' => $params['remark']]);
  98. } else {
  99. $admin = AdminModel::create($params);
  100. //插入user
  101. $params['id'] = $admin->id;
  102. $params['role'] = $role;
  103. User::addCs($params);
  104. }
  105. Db::commit();
  106. } catch (\Exception $e) {
  107. Db::rollback();
  108. return $this->error($e->getMessage());
  109. }
  110. return $this->success([],'操作成功');
  111. }
  112. // 删除管理员
  113. public function delete()
  114. {
  115. try {
  116. $params = (new AdminValidate())->goCheck('del');
  117. // 只允许超级管理员配置
  118. if ($this->admin_id != 1) {
  119. return $this->error('只有超级管理员才能操作');
  120. }
  121. if ($params['id'] == 1) {
  122. return $this->error('超级管理员不能删除');
  123. }
  124. // TP 删除语法
  125. AdminModel::where('id', $params['id'])->delete();
  126. } catch (\Exception $e) {
  127. return $this->error('删除失败:'.$e->getMessage());
  128. }
  129. return $this->success([],'删除成功');
  130. }
  131. /**
  132. * @api {post} /setPassword 修改登录密码
  133. */
  134. public function setPassword()
  135. {
  136. Db::startTrans();
  137. try {
  138. $params = (new AdminValidate())->post()->goCheck('password');
  139. $user = AdminModel::find($this->admin_id);
  140. if (!$user) {
  141. throw new \Exception('用户不存在');
  142. }
  143. // 校验旧密码
  144. if (!password_verify($params['old_password'], $user->password)) {
  145. throw new \Exception('密码错误');
  146. }
  147. // 更新登录密码
  148. $user->password = password_hash($params['password'], PASSWORD_DEFAULT);
  149. $user->save();
  150. Db::commit();
  151. } catch (\Exception $e) {
  152. Db::rollback();
  153. return $this->error($e->getMessage());
  154. }
  155. }
  156. /**
  157. * @api {post} /login 管理员登录
  158. */
  159. public function login()
  160. {
  161. // 登录无需事务,移除多余的 Db::startTrans()
  162. try {
  163. $params = (new AdminValidate())->post()->goCheck('login');
  164. $admin = AdminModel::where('username', $params['username'])->find();
  165. if (!$admin) {
  166. throw new \Exception('账号不存在');
  167. }
  168. if (!password_verify($params['password'], $admin->password)) {
  169. throw new \Exception('密码错误');
  170. }
  171. // 获取角色权限(优化 TP 查询语法)
  172. if ($admin->role_id && $admin->id > 1) {
  173. $admin->role_menu = RoleMenu::alias('rm')
  174. ->join('menu m', 'rm.menu_id = m.id','left')
  175. ->where('rm.role_id', $admin->role_id)
  176. ->where('m.status', 1)
  177. ->field(['m.id', 'm.parent_id', 'm.type', 'm.name', 'm.perms', 'm.paths', 'm.component', 'm.params', 'm.is_cache', 'm.sort'])
  178. ->order('m.sort', 'asc')
  179. ->select()
  180. ->toArray();
  181. } else {
  182. $admin->role_menu = Menu::alias('m')
  183. ->where('m.status', 1)
  184. ->field(['m.id', 'm.parent_id', 'm.type', 'm.name', 'm.perms', 'm.paths', 'm.component', 'm.params', 'm.is_cache', 'm.sort'])
  185. ->order('m.sort', 'asc')
  186. ->select()
  187. ->toArray();
  188. }
  189. //如果登录信息中含有client——id则自动进行绑定
  190. $userInfo = User::where('account', $admin->username)->where('role', '>', 0)->find();
  191. if(!$userInfo){
  192. throw new \Exception('用户不存在');
  193. }
  194. if(!empty($params['client_id'])){
  195. $cid = $this->request->header('cid','');
  196. doBindUid($userInfo['user_id'],$params['client_id'],$cid,$this->request->isMobile());
  197. }
  198. $update=[
  199. 'last_login_time' => time(),
  200. 'last_login_ip' => $this->request->ip(),
  201. 'login_count' => Db::raw('login_count+1')
  202. ];
  203. User::where('user_id',$userInfo['user_id'])->update($update);
  204. $userInfo['qrUrl']=getMainHost().'/scan/u/'.encryptIds($userInfo['user_id']);
  205. unset($userInfo['password'],$userInfo['salt']);
  206. $userInfo['displayName']=$userInfo['realname'];
  207. $userInfo['id']=$userInfo['user_id'];
  208. $authToken=User::refreshToken($userInfo,$param['terminal'] ?? 'web', ['id' => $admin->id, 'role_id' => $admin->role_id]);
  209. $data=[
  210. 'sessionId'=>Session::getId(),
  211. 'token' => $authToken,
  212. 'userInfo'=>$userInfo,
  213. 'adminInfo' => $admin,
  214. ];
  215. //判断是否是客服
  216. if ($userInfo['role'] == 3) {
  217. //通知客服签到
  218. wsSendMsg($userInfo['id'],'sign',['is_sign'=>1]);
  219. //添加客服在线时间
  220. KefuTime::addData($admin->id, 2);
  221. //添加客服上线次数
  222. KefuWork::addNum($admin->id, 'online_num');
  223. }
  224. } catch (\Exception $e) {
  225. return $this->error($e->getMessage());
  226. }
  227. return $this->success($data, '登录成功');
  228. }
  229. //退出登录
  230. public function logout(){
  231. try {
  232. $jwtData = JWTAuth::auth();
  233. } catch (\Exception $e) {
  234. return success(lang('退出成功'));
  235. }
  236. $userInfo = $jwtData['info']->getValue();
  237. //解密token中的用户信息
  238. $userInfo = str_encipher($userInfo,false, config('app.aes_token_key'));
  239. if (!$userInfo) {
  240. return success(lang('退出成功'));
  241. }
  242. //解析json
  243. $userInfo = (array)json_decode($userInfo, true);
  244. if($userInfo){
  245. wsSendMsg(0,'isOnline',['id'=>$userInfo['user_id'],'is_online'=>0]);
  246. //结束客服在线时间
  247. KefuTime::endData($this->admin_id, 2);
  248. }
  249. JWTAuth::invalidate(JWTAuth::token()->get());
  250. return success(lang('退出成功'));
  251. }
  252. }