Admin.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 = AdminModel::getRole($params['role_id']);
  96. if (!empty($id)) {
  97. unset($params['username']);
  98. AdminModel::where('id', $id)->update($params);
  99. User::where('uid', $id)->where('from', 0)->update(['role' => $role, 'realname' => $params['nickname'], 'phone' => $params['phone'], 'remark' => $params['remark']]);
  100. } else {
  101. $admin = AdminModel::create($params);
  102. //插入user
  103. $params['id'] = $admin->id;
  104. $params['role'] = $role;
  105. User::addCs($params);
  106. }
  107. Db::commit();
  108. } catch (\Exception $e) {
  109. Db::rollback();
  110. return $this->error($e->getMessage());
  111. }
  112. return $this->success([],'操作成功');
  113. }
  114. // 删除管理员
  115. public function delete()
  116. {
  117. try {
  118. $params = (new AdminValidate())->goCheck('del');
  119. // 只允许超级管理员配置
  120. if ($this->admin_id != 1) {
  121. return $this->error('只有超级管理员才能操作');
  122. }
  123. if ($params['id'] == 1) {
  124. return $this->error('超级管理员不能删除');
  125. }
  126. // TP 删除语法
  127. AdminModel::where('id', $params['id'])->delete();
  128. } catch (\Exception $e) {
  129. return $this->error('删除失败:'.$e->getMessage());
  130. }
  131. return $this->success([],'删除成功');
  132. }
  133. /**
  134. * @api {post} /setPassword 修改登录密码
  135. */
  136. public function setPassword()
  137. {
  138. Db::startTrans();
  139. try {
  140. $params = (new AdminValidate())->post()->goCheck('password');
  141. $user = AdminModel::find($this->admin_id);
  142. if (!$user) {
  143. throw new \Exception('用户不存在');
  144. }
  145. // 校验旧密码
  146. if (!password_verify($params['old_password'], $user->password)) {
  147. throw new \Exception('密码错误');
  148. }
  149. // 更新登录密码
  150. $user->password = password_hash($params['password'], PASSWORD_DEFAULT);
  151. $user->save();
  152. Db::commit();
  153. } catch (\Exception $e) {
  154. Db::rollback();
  155. return $this->error($e->getMessage());
  156. }
  157. }
  158. /**
  159. * @api {post} /login 管理员登录
  160. */
  161. public function login()
  162. {
  163. // 登录无需事务,移除多余的 Db::startTrans()
  164. try {
  165. $params = (new AdminValidate())->post()->goCheck('login');
  166. $admin = AdminModel::where('username', $params['username'])->find();
  167. if (!$admin) {
  168. throw new \Exception('账号不存在');
  169. }
  170. if (!password_verify($params['password'], $admin->password)) {
  171. throw new \Exception('密码错误');
  172. }
  173. // 获取角色权限(优化 TP 查询语法)
  174. if ($admin->role_id && $admin->id > 1) {
  175. $admin->role_menu = RoleMenu::alias('rm')
  176. ->join('menu m', 'rm.menu_id = m.id','left')
  177. ->where('rm.role_id', $admin->role_id)
  178. ->where('m.status', 1)
  179. ->field(['m.id', 'm.parent_id', 'm.type', 'm.name', 'm.perms', 'm.paths', 'm.component', 'm.params', 'm.is_cache', 'm.sort'])
  180. ->order('m.sort', 'asc')
  181. ->select()
  182. ->toArray();
  183. } else {
  184. $admin->role_menu = Menu::alias('m')
  185. ->where('m.status', 1)
  186. ->field(['m.id', 'm.parent_id', 'm.type', 'm.name', 'm.perms', 'm.paths', 'm.component', 'm.params', 'm.is_cache', 'm.sort'])
  187. ->order('m.sort', 'asc')
  188. ->select()
  189. ->toArray();
  190. }
  191. $admin->role_name = Role::where('id', $admin->role_id)->value('name');
  192. $admin->department_name = Department::where('id', $admin->department_id)->value('name');
  193. //如果登录信息中含有client——id则自动进行绑定
  194. $userInfo = User::where('account', $admin->username)->where('role', '>', 0)->find();
  195. if(!$userInfo){
  196. throw new \Exception('用户不存在');
  197. }
  198. if(!empty($params['client_id'])){
  199. $cid = $this->request->header('cid','');
  200. doBindUid($userInfo['user_id'],$params['client_id'],$cid,$this->request->isMobile());
  201. }
  202. $update=[
  203. 'last_login_time' => time(),
  204. 'last_login_ip' => $this->request->ip(),
  205. 'login_count' => Db::raw('login_count+1')
  206. ];
  207. User::where('user_id',$userInfo['user_id'])->update($update);
  208. $userInfo['qrUrl']=getMainHost().'/scan/u/'.encryptIds($userInfo['user_id']);
  209. unset($userInfo['password'],$userInfo['salt']);
  210. $userInfo['displayName']=$userInfo['realname'];
  211. $userInfo['id']=$userInfo['user_id'];
  212. $authToken=User::refreshToken($userInfo,$param['terminal'] ?? 'web', ['id' => $admin->id, 'role_id' => $admin->role_id]);
  213. $data=[
  214. 'sessionId'=>Session::getId(),
  215. 'token' => $authToken,
  216. 'userInfo'=>$userInfo,
  217. 'adminInfo' => $admin,
  218. ];
  219. //判断是否是客服
  220. if ($userInfo['role'] == 3) {
  221. //通知客服签到
  222. wsSendMsg($userInfo['id'],'sign',['is_sign'=>1]);
  223. //添加客服在线时间
  224. KefuTime::addData($admin->id, 2);
  225. //添加客服上线次数
  226. KefuWork::addNum($admin->id, 'online_num');
  227. }
  228. } catch (\Exception $e) {
  229. return $this->error($e->getMessage());
  230. }
  231. return $this->success($data, '登录成功');
  232. }
  233. //退出登录
  234. public function logout(){
  235. try {
  236. $jwtData = JWTAuth::auth();
  237. } catch (\Exception $e) {
  238. return success(lang('退出成功'));
  239. }
  240. $userInfo = $jwtData['info']->getValue();
  241. //解密token中的用户信息
  242. $userInfo = str_encipher($userInfo,false, config('app.aes_token_key'));
  243. if (!$userInfo) {
  244. return success(lang('退出成功'));
  245. }
  246. //解析json
  247. $userInfo = (array)json_decode($userInfo, true);
  248. if($userInfo){
  249. wsSendMsg(0,'isOnline',['id'=>$userInfo['user_id'],'is_online'=>0]);
  250. //结束客服在线时间
  251. KefuTime::endData($this->admin_id, 2);
  252. }
  253. JWTAuth::invalidate(JWTAuth::token()->get());
  254. return success(lang('退出成功'));
  255. }
  256. }