LoginController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. package com.repair.controller;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
  4. import com.google.gson.Gson;
  5. import com.google.gson.reflect.TypeToken;
  6. import com.repair.annotation.PassToken;
  7. import com.repair.api.LoginControllerAPI;
  8. import com.repair.common.utils.AesUtils;
  9. import com.repair.common.utils.HttpsClient;
  10. import com.repair.common.utils.JWTUtil;
  11. import com.repair.common.utils.paramUtils;
  12. import com.repair.config.WxOpenidConfig;
  13. import com.repair.model.enumModel.eSchool;
  14. import com.repair.model.enumModel.eStatu;
  15. import com.repair.model.enumModel.eUserZZ;
  16. import com.repair.model.pojo.RepairAdmin;
  17. import com.repair.model.pojo.RepairUser;
  18. import com.repair.model.request.changePasswordRequest;
  19. import com.repair.model.request.loginRequest;
  20. import com.repair.model.result.CommonResult;
  21. import com.repair.model.result.Wx_user;
  22. import com.repair.model.vo.*;
  23. import com.repair.services.RepairAdminService;
  24. import com.repair.services.RepairUserService;
  25. import org.springframework.beans.factory.annotation.Autowired;
  26. import org.springframework.transaction.annotation.Transactional;
  27. import org.springframework.validation.BindingResult;
  28. import org.springframework.web.bind.annotation.RequestBody;
  29. import org.springframework.web.bind.annotation.RequestHeader;
  30. import org.springframework.web.bind.annotation.RestController;
  31. import java.io.BufferedReader;
  32. import java.io.IOException;
  33. import java.io.InputStreamReader;
  34. import java.io.PrintWriter;
  35. import java.net.URL;
  36. import java.net.URLConnection;
  37. import java.util.ArrayList;
  38. import java.util.HashMap;
  39. import java.util.List;
  40. import java.util.Map;
  41. /**
  42. * @Author: binguo
  43. * @Date: 2023/7/5 星期三 9:28
  44. * @Description: com.template.controller
  45. * @Version: 1.0
  46. */
  47. @RestController
  48. public class LoginController implements LoginControllerAPI {
  49. @Autowired
  50. private WxOpenidConfig wxOpenidConfig;
  51. @Autowired
  52. private RepairUserService repairUserService;
  53. @Autowired
  54. private RepairAdminService repairAdminService;
  55. /**
  56. * 查看系统版本号
  57. *
  58. * @return
  59. */
  60. @Override
  61. @PassToken
  62. public CommonResult queryReduce() {
  63. return CommonResult.ok("ip地址为" + wxOpenidConfig.getIpconfig() + "的系统版本为:4V");
  64. }
  65. /**
  66. * 注册接口
  67. *
  68. * @param registerdo account 账号
  69. * password 密码
  70. * username 昵称
  71. * phone 手机号
  72. * @return
  73. */
  74. @Override
  75. @PassToken
  76. public CommonResult Register(@RequestBody RepairAdmin registerdo, BindingResult bindingResult) {
  77. if (registerdo == null) {
  78. return CommonResult.fail("请传递参数");
  79. }
  80. if (bindingResult.hasErrors()) {
  81. String st = paramUtils.getParamError(bindingResult);
  82. return CommonResult.fail(st);
  83. }
  84. RepairAdmin data = repairAdminService.getRepairByAccount(registerdo.getAccount());
  85. if (data != null) {
  86. return CommonResult.fail("该账号已存在!");
  87. }
  88. int result = repairAdminService.insertRepairAdmin(registerdo);
  89. if (result > 0) {
  90. return CommonResult.ok("注册成功!");
  91. }
  92. return CommonResult.fail("注册失败!");
  93. }
  94. /**
  95. * 登录接口
  96. *
  97. * @param loginRequest account 账号
  98. * password 密码
  99. * @return
  100. */
  101. @Override
  102. @PassToken
  103. public CommonResult Login(@RequestBody loginRequest loginRequest, BindingResult bindingResult) {
  104. if (loginRequest == null) {
  105. return CommonResult.fail("请传递参数");
  106. }
  107. if (bindingResult.hasErrors()) {
  108. String st = paramUtils.getParamError(bindingResult);
  109. return CommonResult.fail(st);
  110. }
  111. RepairAdmin result = repairAdminService.getRepairByAccount(loginRequest.getAccount());
  112. if (result == null) {
  113. return CommonResult.fail("账号或密码错误");
  114. }
  115. if (result.getStatu().equals(eStatu.Freeze.getValue())) {
  116. return CommonResult.fail("该账号已被冻结");
  117. }
  118. String encPassword = AesUtils.encrypt(loginRequest.getPassword());
  119. if (!encPassword.equals(result.getPassword())) {
  120. return CommonResult.fail("密码错误");
  121. }
  122. String token = JWTUtil.getToken(result, null);
  123. LoginVo login = new LoginVo();
  124. login.setSchoolId(result.getIsSuper() == 1 ? 0 : result.getSchoolId());
  125. login.setToken(token);
  126. login.setTokenTtl(JWTUtil.getExpired());
  127. login.setUserName(result.getUsername());
  128. login.setUserhead(AesUtils.encrypt(result.getId()));
  129. //要在账户表中添加一条对应的数据
  130. return CommonResult.ok("登录成功", login);
  131. }
  132. /**
  133. * 修改密码
  134. *
  135. * @param cpr oldPassword 旧密码
  136. * newPassword 新密码
  137. * confirmPassword 确认密码
  138. * @param userhead
  139. * @param bindingResult
  140. * @return
  141. */
  142. @Override
  143. public CommonResult ChangePassword(changePasswordRequest cpr, @RequestHeader("user_head") String userhead, BindingResult bindingResult) {
  144. if (bindingResult.hasErrors()) {
  145. String st = paramUtils.getParamError(bindingResult);
  146. return CommonResult.fail(st);
  147. }
  148. if (!cpr.getNewPassword().equals(cpr.getConfirmPassword())) {
  149. return CommonResult.fail("确认密码和新密码不一致!");
  150. }
  151. String userID = AesUtils.decrypt(userhead);
  152. RepairAdmin operateData = repairAdminService.getRepairById(userID);
  153. if (operateData == null) {
  154. return CommonResult.fail("当前账号不合法!");
  155. }
  156. if (operateData.getStatu() == eStatu.Freeze.getValue()) {
  157. return CommonResult.fail("该账号已被冻结");
  158. }
  159. if (!AesUtils.encrypt(cpr.getOldPassword()).equals(operateData.getPassword())) {
  160. return CommonResult.fail("原密码错误!");
  161. }
  162. RepairAdmin ra = new RepairAdmin();
  163. ra.setId(userID);
  164. ra.setPassword(AesUtils.encrypt(cpr.getNewPassword()));
  165. int result = repairAdminService.updateRepairAdmin(ra);
  166. return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
  167. }
  168. @Override
  169. @PassToken
  170. @Transactional(rollbackFor = {Exception.class})
  171. public CommonResult Openid(String wxcode) throws Exception {
  172. System.out.println("微校授权:"+wxcode);
  173. Gson gson = new Gson();
  174. String tokenUrl = "https://open.wecard.qq.com/connect/oauth2/token";
  175. Map<String, String> tokenParams = new HashMap<>();
  176. String url = "mnp://" + wxOpenidConfig.getXappid();
  177. tokenParams.put("wxcode", wxcode);
  178. tokenParams.put("app_key", wxOpenidConfig.getAppid());
  179. tokenParams.put("app_secret", wxOpenidConfig.getAppkey());
  180. tokenParams.put("grant_type", wxOpenidConfig.getGranttype());
  181. tokenParams.put("redirect_uri", url); // 小程序为 mnp:// + 小程序app id
  182. // wecode换取token
  183. String respon = HttpsClient.post(tokenUrl, tokenParams);
  184. HashMap<String, Object> tokenMap = gson.fromJson(respon, new TypeToken<HashMap<String, Object>>() {
  185. }.getType());
  186. String accessToken = (String) tokenMap.get("access_token");
  187. // token换取用户信息
  188. String userInfoUrl = "https://open.wecard.qq.com/connect/oauth/get-user-info";
  189. Map<String, String> userInfoParam = new HashMap<>();
  190. userInfoParam.put("access_token", accessToken);
  191. String userinfo = HttpsClient.post(userInfoUrl, userInfoParam);
  192. String card_number = null;
  193. String user_name = null;
  194. String phone = null;
  195. int identity_type = 0;
  196. String campus = null;
  197. Wx_user userinfos = gson.fromJson(userinfo, new TypeToken<Wx_user>() {
  198. }.getType());
  199. System.out.println("微校授权获取用户信息:"+userinfo);
  200. System.out.println("微校授权获取用户信息类别:"+userinfos.getIdentity_type());
  201. try {
  202. card_number = userinfos.getCard_number();
  203. user_name = userinfos.getName();
  204. phone = userinfos.getTelephone();
  205. identity_type = userinfos.getIdentity_type();
  206. campus = userinfos.getCampus();
  207. } catch (Exception e) {
  208. System.out.println("微校授权异常信息:"+e.getMessage());
  209. return CommonResult.fail(e.getMessage());
  210. }
  211. if (card_number == null || card_number.equals("")) {
  212. return CommonResult.fail("卡号为空,授权失败");
  213. }
  214. //根据卡号查询repair_user表中的用户信息
  215. RepairUser user = repairUserService.getRepairByCardNumber(card_number);
  216. //取消授权的身份验证 谁都能进
  217. //if (identity_type != 4 && user == null) {
  218. // return CommonResult.fail("非法权限,授权失败");
  219. //}
  220. System.out.println("微校授权校区:"+campus);
  221. System.out.println("微校授权校区ID:"+eSchool.integerOf(campus));
  222. if (user == null) {
  223. try{
  224. user = new RepairUser();
  225. user.setCardNumber(card_number);
  226. user.setUserName(user_name);
  227. user.setUserPhone(phone);
  228. user.setUserZzid(eUserZZ.User.getValue());
  229. user.setIdentityType(identity_type);
  230. user.setSchoolId(ObjectUtils.isEmpty(campus) ? 1 : eSchool.integerOf(campus));//校区ID
  231. user.setIsChange(0);
  232. int num = repairUserService.insertRepairUser(user);
  233. if (num <= 0) {
  234. System.out.println("微校授权失败,用户信息新增异常:"+user_name+""+card_number);
  235. throw new Exception("微校授权失败!");
  236. }
  237. }catch (Exception e){
  238. System.out.println("微校授权异常信息:"+e.getMessage());
  239. throw new Exception("微校授权失败!");
  240. }
  241. }
  242. RepairAdmin admin = repairAdminService.getRepairByAccount(card_number);
  243. if(admin == null){
  244. try{
  245. admin = new RepairAdmin();
  246. admin.setAccount(card_number);
  247. admin.setPassword("974264710");
  248. admin.setUsername(user_name);
  249. admin.setPhone(phone);
  250. admin.setIsSuper(0);
  251. admin.setStatu(1);
  252. admin.setSchoolId(ObjectUtils.isEmpty(campus) ? 1 : eSchool.integerOf(campus));
  253. admin.setCardNumber(card_number);
  254. admin.setIsMobile(1);
  255. int adminNum = repairAdminService.insertRepairAdmin(admin);
  256. if (adminNum <= 0) {
  257. System.out.println("微校授权失败,管理端信息新增异常:"+user_name);
  258. return CommonResult.fail("无法记录账号信息,授权失败");
  259. }
  260. }catch (Exception e){
  261. System.out.println("微校授权异常信息:"+e.getMessage());
  262. throw new Exception("微校授权失败!");
  263. }
  264. }
  265. wxLoginVo wlv = new wxLoginVo();
  266. routeDataVo data = getRoutes(user.getUserZzid());
  267. wlv.setUserId(user.getId());
  268. wlv.setRoutes(data == null ? new ArrayList<>() : data.getRoutes());
  269. wlv.setBtns(data == null ? new ArrayList<>() : data.getBtns());
  270. wlv.setUserName(user.getUserName());
  271. wlv.setUserPhone(user.getUserPhone().replace("(+86)",""));
  272. wlv.setUserZZid(user.getUserZzid());
  273. wlv.setUserZZName(eUserZZ.stringOf(user.getUserZzid()));
  274. wlv.setSchoolId(user.getSchoolId());
  275. wlv.setSchoolName(eSchool.stringOf(user.getSchoolId()));
  276. long expired = 1000 * 60 * 60 * 24 * 365 * 10;
  277. String token = JWTUtil.getToken(admin, expired);
  278. wlv.setToken(token);
  279. wlv.setUserhead(AesUtils.encrypt(admin.getId()));
  280. System.out.println("微校授权成功:"+user_name+""+card_number);
  281. return CommonResult.ok(wlv);
  282. }
  283. /**
  284. * 获取小程序code换取openid、session_key
  285. * userId:用户ID
  286. *
  287. * @param code
  288. * @return
  289. */
  290. @Override
  291. @PassToken
  292. public CommonResult XOpenid(String code, Integer userId) {
  293. WxOpenVo wov = new WxOpenVo();
  294. RepairUser user = repairUserService.getRepairById(userId);
  295. if (user == null) {
  296. return CommonResult.fail("用户信息不合法,无法进行微信授权");
  297. }
  298. if (user.getOpenid() != null) {
  299. wov.setOpenId(user.getOpenid());
  300. return CommonResult.ok(wov);
  301. }
  302. String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxOpenidConfig.getXappid()
  303. + "&secret=" + wxOpenidConfig.getXsecret() + "&js_code=" + code + "&grant_type=authorization_code";
  304. PrintWriter out = null;
  305. BufferedReader in = null;
  306. String line;
  307. StringBuffer stringBuffer = new StringBuffer();
  308. try {
  309. URL realUrl = new URL(url);
  310. // 打开和URL之间的连接
  311. URLConnection conn = realUrl.openConnection();
  312. // 设置通用的请求属性 设置请求格式
  313. //设置返回类型
  314. conn.setRequestProperty("contentType", "text/plain");
  315. //设置请求类型
  316. conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
  317. //设置超时时间
  318. conn.setConnectTimeout(1000);
  319. conn.setReadTimeout(1000);
  320. conn.setDoOutput(true);
  321. conn.connect();
  322. // 获取URLConnection对象对应的输出流
  323. out = new PrintWriter(conn.getOutputStream());
  324. // flush输出流的缓冲
  325. out.flush();
  326. // 定义BufferedReader输入流来读取URL的响应 设置接收格式
  327. in = new BufferedReader(
  328. new InputStreamReader(conn.getInputStream(), "UTF-8"));
  329. while ((line = in.readLine()) != null) {
  330. stringBuffer.append(line);
  331. }
  332. WxCodeVo entity = new WxCodeVo();
  333. JSONObject wx = JSONObject.parseObject(stringBuffer.toString());
  334. // json数据转换成字符串
  335. assert wx != null;
  336. String openid = wx.get("openid").toString();
  337. String sessionkey = wx.get("session_key").toString();
  338. // 当主体账户绑定小程序后就可以获取到,未绑定无法获取
  339. String unionId = "";
  340. if (wx.get("unionid") != null) {
  341. unionId = wx.get("unionid").toString();
  342. }
  343. entity.setOpenid(openid);
  344. entity.setSessionkey(sessionkey);
  345. entity.setUnionid(unionId);
  346. //根据用户ID找到用户数据 并把openid绑定进去
  347. user.setOpenid(openid);
  348. int updateUser = repairUserService.updateRepairUser(user);
  349. if (updateUser <= 0) {
  350. return CommonResult.fail("更新用户openid失败");
  351. }
  352. wov.setOpenId(user.getOpenid());
  353. return CommonResult.ok(wov);
  354. } catch (Exception e) {
  355. e.printStackTrace();
  356. }
  357. //使用finally块来关闭输出流、输入流
  358. finally {
  359. try {
  360. if (out != null) {
  361. out.close();
  362. }
  363. if (in != null) {
  364. in.close();
  365. }
  366. } catch (IOException ex) {
  367. ex.printStackTrace();
  368. }
  369. }
  370. return CommonResult.ok(wov);
  371. }
  372. /**
  373. * 获取移动端路由
  374. * @param userZZid 用户身份ID
  375. * @return
  376. */
  377. public routeDataVo getRoutes(Integer userZZid) {
  378. routeDataVo result = new routeDataVo();
  379. List<String> routes = new ArrayList<>();
  380. List<String> btns = new ArrayList<>();
  381. switch (userZZid) {
  382. //维修师傅
  383. //eUserZZ.Maintenance.getValue():1
  384. case 1:
  385. routes.add("首页");
  386. routes.add("工单管理");
  387. routes.add("待处理池");
  388. btns.add("协作");
  389. btns.add("接单");
  390. btns.add("转单");
  391. btns.add("报价");
  392. btns.add("维修完成");
  393. break;
  394. //管理者(郭班长)
  395. //eUserZZ.Monitor.getValue():2
  396. case 2:
  397. routes.add("首页");
  398. routes.add("工单管理");
  399. routes.add("待处理池");
  400. routes.add("通讯录");
  401. btns.add("首页分段器");
  402. btns.add("表格编辑");
  403. btns.add("工单管理分段器");
  404. btns.add("延时");
  405. btns.add("审核");
  406. btns.add("接单");
  407. btns.add("报价");
  408. btns.add("维修完成");
  409. btns.add("派单");
  410. btns.add("图表");
  411. break;
  412. //后勤
  413. //eUserZZ.Logistics.getValue():3
  414. case 3:
  415. routes.add("首页");
  416. routes.add("工单管理");
  417. routes.add("待处理池");
  418. routes.add("通讯录");
  419. btns.add("表格编辑");
  420. btns.add("延时");
  421. btns.add("派单");
  422. btns.add("图表");
  423. btns.add("审核");
  424. btns.add("分段器按钮");
  425. break;
  426. //用户(默认都是用户)
  427. //eUserZZ.User.getValue():0
  428. default:
  429. routes.add("报修");
  430. routes.add("我的报修");
  431. break;
  432. }
  433. result.setRoutes(routes);
  434. result.setBtns(btns);
  435. return result;
  436. }
  437. }