Admin.php 10 KB

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