Admin.php 9.7 KB

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