TBUserController.java 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. package com.qmth.themis.backend.api;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.google.gson.Gson;
  6. import com.qmth.themis.business.annotation.ApiJsonObject;
  7. import com.qmth.themis.business.annotation.ApiJsonProperty;
  8. import com.qmth.themis.business.constant.SystemConstant;
  9. import com.qmth.themis.business.dto.AuthDto;
  10. import com.qmth.themis.business.dto.MqDto;
  11. import com.qmth.themis.business.dto.response.TBUserDto;
  12. import com.qmth.themis.business.entity.TBOrg;
  13. import com.qmth.themis.business.entity.TBSession;
  14. import com.qmth.themis.business.entity.TBUser;
  15. import com.qmth.themis.business.entity.TBUserRole;
  16. import com.qmth.themis.business.enums.FieldUniqueEnum;
  17. import com.qmth.themis.business.enums.MqTagEnum;
  18. import com.qmth.themis.business.enums.MqTopicEnum;
  19. import com.qmth.themis.business.enums.SystemOperationEnum;
  20. import com.qmth.themis.business.service.*;
  21. import com.qmth.themis.business.util.EhcacheUtil;
  22. import com.qmth.themis.business.util.RedisUtil;
  23. import com.qmth.themis.business.util.ServletUtil;
  24. import com.qmth.themis.business.util.SessionUtil;
  25. import com.qmth.themis.common.contanst.Constants;
  26. import com.qmth.themis.common.enums.ExceptionResultEnum;
  27. import com.qmth.themis.common.enums.Platform;
  28. import com.qmth.themis.common.enums.Source;
  29. import com.qmth.themis.common.exception.BusinessException;
  30. import com.qmth.themis.common.signature.SignatureInfo;
  31. import com.qmth.themis.common.signature.SignatureType;
  32. import com.qmth.themis.common.util.AesUtil;
  33. import com.qmth.themis.common.util.Result;
  34. import com.qmth.themis.common.util.ResultUtil;
  35. import io.swagger.annotations.*;
  36. import org.apache.commons.lang3.RandomStringUtils;
  37. import org.slf4j.Logger;
  38. import org.slf4j.LoggerFactory;
  39. import org.springframework.dao.DuplicateKeyException;
  40. import org.springframework.transaction.annotation.Transactional;
  41. import org.springframework.web.bind.annotation.*;
  42. import javax.annotation.Resource;
  43. import java.security.NoSuchAlgorithmException;
  44. import java.util.*;
  45. /**
  46. * @Description: 用户 前端控制器
  47. * @Param:
  48. * @return:
  49. * @Author: wangliang
  50. * @Date: 2020/6/25
  51. */
  52. @Api(tags = "用户Controller")
  53. @RestController
  54. @RequestMapping("/${prefix.url.admin}/user")
  55. public class TBUserController {
  56. private final static Logger log = LoggerFactory.getLogger(TBUserController.class);
  57. @Resource
  58. TBUserService tbUserService;
  59. @Resource
  60. CacheService cacheService;
  61. @Resource
  62. RedisUtil redisUtil;
  63. @Resource
  64. MqDtoService mqDtoService;
  65. @Resource
  66. TBUserRoleService tbUserRoleService;
  67. @Resource
  68. TBOrgService tbOrgService;
  69. @ApiOperation(value = "用户登录接口")
  70. @RequestMapping(value = "/login/account", method = RequestMethod.POST)
  71. @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = TBUser.class)})
  72. public Result login(@ApiJsonObject(name = "loginAccount", value = {
  73. @ApiJsonProperty(key = "loginName", description = "登录名"),
  74. @ApiJsonProperty(key = "password", description = "密码"),
  75. @ApiJsonProperty(key = "code", description = "机构代码")
  76. }) @ApiParam(value = "用户信息", required = true) @RequestBody Map<String, Object> mapParameter) throws NoSuchAlgorithmException {
  77. if (Objects.isNull(mapParameter)) {
  78. throw new BusinessException(ExceptionResultEnum.USER_INFO_IS_NULL);
  79. }
  80. if (Objects.isNull(mapParameter.get("loginName")) || Objects.equals(mapParameter.get("loginName"), "")) {
  81. throw new BusinessException(ExceptionResultEnum.LOGIN_NAME_IS_NULL);
  82. }
  83. if (Objects.isNull(mapParameter.get("password")) || Objects.equals(mapParameter.get("password"), "")) {
  84. throw new BusinessException(ExceptionResultEnum.PASSWORD_IS_NULL);
  85. }
  86. if (Objects.isNull(mapParameter.get("code")) || Objects.equals(mapParameter.get("code"), "")) {
  87. throw new BusinessException(ExceptionResultEnum.ORG_CODE_IS_NULL);
  88. }
  89. String loginName = String.valueOf(mapParameter.get("loginName"));
  90. String password = String.valueOf(mapParameter.get("password"));
  91. String orgCode = String.valueOf(mapParameter.get("code"));
  92. TBOrg tbOrg = (TBOrg) EhcacheUtil.get(SystemConstant.orgCodeCache, orgCode);
  93. if (Objects.isNull(tbOrg)) {
  94. QueryWrapper<TBOrg> tbOrgQueryWrapper = new QueryWrapper<>();
  95. tbOrgQueryWrapper.lambda().eq(TBOrg::getCode, orgCode);
  96. tbOrg = tbOrgService.getOne(tbOrgQueryWrapper);
  97. if (Objects.nonNull(tbOrg)) {
  98. EhcacheUtil.put(SystemConstant.orgCodeCache, orgCode, tbOrg);
  99. }
  100. }
  101. if (Objects.isNull(tbOrg)) {
  102. throw new BusinessException(ExceptionResultEnum.ORG_NO);
  103. }
  104. QueryWrapper<TBUser> wrapper = new QueryWrapper<>();
  105. wrapper.lambda().eq(TBUser::getLoginName, loginName);
  106. TBUser user = tbUserService.getOne(wrapper);
  107. //用户不存在
  108. if (Objects.isNull(user)) {
  109. throw new BusinessException(ExceptionResultEnum.USER_NO);
  110. }
  111. if (Objects.nonNull(user.getOrgId()) && user.getOrgId().longValue() != tbOrg.getId().longValue()) {
  112. throw new BusinessException("用户机构不匹配");
  113. }
  114. String loginPassword = AesUtil.decryptCs7(password, Constants.AES_RULE);
  115. //密码错误
  116. String aesPassword = AesUtil.decryptCs7(user.getPassword(), Constants.AES_RULE);
  117. if (!Objects.equals(loginPassword, aesPassword)) {
  118. throw new BusinessException(ExceptionResultEnum.PASSWORD_ERROR);
  119. }
  120. return userLoginCommon(user);
  121. }
  122. @ApiOperation(value = "短信验证码登陆接口")
  123. @RequestMapping(value = "/login/verifyCode", method = RequestMethod.POST)
  124. @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = TBUser.class)})
  125. public Result verifyCode(@ApiParam(value = "用户信息", required = true) @RequestBody Map<String, Object> mapParameter) throws NoSuchAlgorithmException {
  126. if (Objects.isNull(mapParameter.get("loginName")) || Objects.equals(mapParameter.get("loginName"), "")) {
  127. throw new BusinessException(ExceptionResultEnum.LOGIN_NAME_IS_NULL);
  128. }
  129. if (Objects.isNull(mapParameter.get("verifyCode")) || Objects.equals(mapParameter.get("verifyCode"), "")) {
  130. throw new BusinessException(ExceptionResultEnum.VERIFYCODE_IS_NULL);
  131. }
  132. String loginName = String.valueOf(mapParameter.get("loginName"));
  133. String verifyCode = String.valueOf(mapParameter.get("verifyCode"));
  134. QueryWrapper<TBUser> wrapper = new QueryWrapper<>();
  135. wrapper.lambda().eq(TBUser::getLoginName, loginName);
  136. TBUser user = tbUserService.getOne(wrapper);
  137. //用户不存在
  138. if (Objects.isNull(user)) {
  139. throw new BusinessException(ExceptionResultEnum.USER_NO);
  140. }
  141. //todo 加入验证码校验逻辑
  142. return userLoginCommon(user);
  143. }
  144. /**
  145. * 用户登录公用
  146. *
  147. * @param user
  148. * @return
  149. * @throws NoSuchAlgorithmException
  150. */
  151. public Result userLoginCommon(TBUser user) throws NoSuchAlgorithmException {
  152. //停用
  153. if (user.getEnable().intValue() == 0) {
  154. throw new BusinessException(ExceptionResultEnum.USER_ENABLE);
  155. }
  156. Platform platform = Platform.valueOf(ServletUtil.getRequestPlatform());
  157. String deviceId = ServletUtil.getRequestDeviceId();
  158. //添加用户鉴权缓存
  159. AuthDto authDto = cacheService.addAccountCache(user.getId());
  160. //生成token
  161. String token = RandomStringUtils.randomAlphanumeric(32);
  162. //添加用户缓存
  163. redisUtil.setUser(user.getId(), user);
  164. String source = null;
  165. if (Objects.equals(platform.name(), Platform.WIN.name()) || Objects.equals(platform.name(), Platform.MAC.name()) || Objects.equals(platform.name(), Platform.IOS.name()) || Objects.equals(platform.name(), Platform.ANDROID.name())) {
  166. source = platform.getSource().split(",")[0];
  167. } else {
  168. source = platform.getSource();
  169. }
  170. //添加用户会话缓存
  171. String sessionId = SessionUtil.digest(user.getId(), Math.abs(authDto.getRoleCodes().toString().hashCode()), source);
  172. Map<String, Object> expireMap = SystemConstant.getExpireTime(platform);
  173. Date expire = (Date) expireMap.get("date");
  174. Long redisExpire = Long.parseLong(String.valueOf(expireMap.get("redisExpire")));
  175. TBSession tbSession = new TBSession(sessionId, String.valueOf(user.getId()), authDto.getRoleCodes().toString(), source, platform.name(), deviceId, ServletUtil.getRequest().getLocalAddr(), token, expire.getTime());
  176. redisUtil.setUserSession(sessionId, tbSession, redisExpire);
  177. //mq发送消息start
  178. MqDto mqDto = new MqDto(MqTopicEnum.THEMIS_TOPIC.getCode(), platform.name(), tbSession, MqTagEnum.valueOf(platform.name()), tbSession.getId(), user.getLoginName());
  179. mqDtoService.assembleSendOneWayMsg(mqDto);
  180. MqDto mqDtoLog = new MqDto(MqTopicEnum.THEMIS_TOPIC.getCode(), MqTagEnum.USER.name(), SystemOperationEnum.LOGIN, MqTagEnum.USER, String.valueOf(user.getId()), user.getLoginName());
  181. mqDtoService.assembleSendOneWayMsg(mqDtoLog);
  182. //mq发送消息end
  183. //测试
  184. String test = SignatureInfo.build(SignatureType.TOKEN, sessionId, token);
  185. Map<String, Object> map = new HashMap<>();
  186. // map.put(SystemConstant.ACCESS_TOKEN, token);
  187. map.put(SystemConstant.ACCESS_TOKEN, test);
  188. map.put(SystemConstant.ACCOUNT, user);
  189. map.put(SystemConstant.SESSION_ID, sessionId);
  190. map.put("roleCodes", authDto.getRoleCodes());
  191. if (Objects.nonNull(authDto.getTbOrg())) {
  192. Map orgMap = new HashMap();
  193. orgMap.put("name", authDto.getTbOrg().getName());
  194. orgMap.put("logo", authDto.getTbOrg().getLogo());
  195. orgMap.put("enableMonitorRecord", authDto.getTbOrg().getEnableMonitorRecord());
  196. map.put(SystemConstant.ORG_INFO, orgMap);
  197. redisUtil.setOrg(authDto.getTbOrg().getId(), authDto.getTbOrg());
  198. }
  199. return ResultUtil.ok(map);
  200. }
  201. // @ApiOperation(value = "es查询接口")
  202. // @RequestMapping(value = "/websocketPush", method = RequestMethod.POST)
  203. // public Result websocketPush(@RequestBody String message) throws IOException {
  204. // TBUser tbUser = (TBUser) ServletUtil.getRequestAccount(request);
  205. // WebSocketServer.sendInfo(message, String.valueOf(tbUser.getId()));
  206. // return ResultUtil.ok(SystemConstant.SUCCESS);
  207. // }
  208. // @Resource
  209. // TEExamActivityService teExamActivityService;
  210. //
  211. // @Resource
  212. // TEExamService teExamService;
  213. //
  214. // @Resource
  215. // TEStudentService teStudentService;
  216. //
  217. // @Resource
  218. // TEExamStudentService teExamStudentService;
  219. //
  220. // @Resource
  221. // TEExamCourseService teExamCourseService;
  222. //
  223. // @Resource
  224. // TEExamPaperService teExamPaperService;
  225. //
  226. // @Value("${db.name}")
  227. // String dbName;
  228. //
  229. // @Resource
  230. // MongoTemplate mongoTemplate;
  231. //
  232. // @Resource
  233. // ETEStudentService eteStudentService;
  234. //
  235. // @Resource
  236. // ETEStudentRepo eteStudentRepo;
  237. // @ApiOperation(value = "es查询接口")
  238. // @RequestMapping(value = "/es/list", method = RequestMethod.POST)
  239. // @Transactional
  240. // public Result esList() {
  241. //// eteStudentService.createIndex();
  242. //// List<ETEStudentEntity> list = new ArrayList<>();
  243. //// for (int i = 0; i < 10; i++) {
  244. //// //学生档案
  245. //// ETEStudentEntity eteStudentEntity = new ETEStudentEntity();
  246. //// eteStudentEntity.setId(Constants.idGen.next());
  247. //// eteStudentEntity.setOrgId(1L);
  248. //// eteStudentEntity.setIdentity("test" + i);
  249. //// eteStudentEntity.setPassword("123456");
  250. //// eteStudentEntity.setIdcardNumber(RandomStringUtils.randomAlphanumeric(18));
  251. //// eteStudentEntity.setMobileNumber(RandomStringUtils.randomNumeric(11));
  252. //// eteStudentEntity.setName("java" + i + RandomStringUtils.randomAlphanumeric(30));
  253. //// eteStudentEntity.setGender(1);
  254. //// eteStudentEntity.setBasePhotoPath("http://11111");
  255. //// eteStudentEntity.setCreateTime(new Date());
  256. //// list.add(eteStudentEntity);
  257. //// }
  258. //// eteStudentService.saveAll(list);
  259. ////// Iterator<ETEStudentEntity> iterator = eteStudentService.findAll();
  260. //// org.springframework.data.domain.Page<ETEStudentEntity> eteStudentEntityPage1 = (org.springframework.data.domain.Page<ETEStudentEntity>) eteStudentService.queryName("2");
  261. ////// List<ETEStudentEntity> eteStudentEntityList = eteStudentService.findByNameLike("java");
  262. //// org.springframework.data.domain.Page<ETEStudentEntity> eteStudentEntityPage2 = (org.springframework.data.domain.Page<ETEStudentEntity>) eteStudentService.queryMobileNumber("2");
  263. ////// Optional<ETEStudentEntity> eteStudentEntity = eteStudentRepo.findById(eteStudentEntityPage.getContent().get(0).getId());
  264. //// Map map = new HashMap();
  265. //// map.put(SystemConstant.RECORDS, eteStudentEntityPage1);
  266. //// map.put(SystemConstant.RECORDS + 2, eteStudentEntityPage2);
  267. ////// map.put("bean", eteStudentEntity.get());
  268. //// return ResultUtil.ok(map);
  269. //
  270. //// for (int i = 0; i < 5; i++) {
  271. //
  272. //// mqDtoService.assembleSendOneWayMsg("imTopic", "teacher", "老师发送的一条消息1", MqEnum.MESSAGE_LOG.name(), "1", "2");
  273. //// mqDtoService.assembleSendOneWayMsg("imTopic", "user", "用户发送的一条消息2", MqEnum.MESSAGE_LOG.name(), "1", "2");
  274. //// mqDtoService.assembleSendOneWayMsg("imTopic", "user", "学生发送的一条消息3", MqEnum.MESSAGE_LOG.name(), "1", "2");
  275. // Map map = new HashMap();
  276. // map.put("sendUserId", "10");
  277. // map.put("toUserId", "20");
  278. // map.put("model", MessageModel.BROADCASTING);
  279. //// map.put("model", MessageModel.CLUSTERING);
  280. // MqDto mqDto = new MqDto("websocketImTopic", "im", "学生发送的一条消息4", MqEnum.MESSAGE_LOG, "1", map, "2");
  281. //// mqDtoService.assembleSendOneWayMsg("imTopic", "user", "学生发送的一条消息3", MqEnum.MESSAGE_LOG.name(), "1", "2");
  282. // mqDtoService.assembleSendOneWayMsg(mqDto);
  283. // // }
  284. // return ResultUtil.ok(SystemConstant.SUCCESS);
  285. // }
  286. // @ApiOperation(value = "用户查询接口")
  287. // @RequestMapping(value = "/list", method = RequestMethod.POST)
  288. // @Transactional
  289. // public Result list() {
  290. // String tableName = "t_e_exam_activity_test1";
  291. // Integer count = teExamActivityService.existTable(tableName, dbName);
  292. // log.info("count:{}", count);
  293. // if (count == 0) {
  294. // teExamActivityService.createNewTable(tableName);
  295. // }
  296. // //学生档案
  297. // TEStudent teStudent = new TEStudent();
  298. // teStudent.setId(Constants.idGen.next());
  299. // teStudent.setOrgId(1L);
  300. // teStudent.setIdentity(RandomStringUtils.randomAlphanumeric(30));
  301. // teStudent.setPassword("123456");
  302. // teStudent.setIdcardNumber(RandomStringUtils.randomAlphanumeric(18));
  303. // teStudent.setMobileNumber(RandomStringUtils.randomNumeric(11));
  304. // teStudent.setName("aaa");
  305. // teStudent.setGender(1);
  306. // teStudent.setBasePhotoPath("http://11111");
  307. // teStudent.setEnable(1);
  308. // teStudentService.save(teStudent);
  309. //
  310. // //考试批次
  311. // TEExam teExam = new TEExam();
  312. // teExam.setId(Constants.idGen.next());
  313. // teExam.setOrgId(1L);
  314. // teExam.setCode(RandomStringUtils.randomAlphanumeric(20));
  315. // teExam.setName("123");
  316. // teExam.setTag("test1");
  317. // teExam.setStartTime(new Date());
  318. // teExam.setEndTime(new Date());
  319. // teExam.setStatus(0);
  320. // teExam.setShortCode("123456");
  321. // teExam.setPrepareSeconds(30);
  322. // teExam.setMinDurationSeconds(30);
  323. // teExam.setPreNotice("99999");
  324. // teExam.setPreNoticeStaySeconds(30);
  325. // teExam.setPostNotice("88888");
  326. // teExam.setExamCount(5);
  327. // teExam.setBreakResumeCount(3);
  328. // teExam.setBreakExpireSeconds(30);
  329. // teExam.setCameraPhotoUpload(1);
  330. // teExam.setReexamAuditing(1);
  331. // teExam.setShowObjectiveScore(1);
  332. // teExam.setMode(0);
  333. // teExam.setEnable(1);
  334. // teExam.setArchived(0);
  335. // teExam.setOpeningSeconds(30);
  336. // teExam.setMaxDurationSeconds(30);
  337. // teExam.setForceFinish(1);
  338. // teExam.setEntryAuthenticationPolicy(1);
  339. // teExam.setInProcessFaceVerify(1);
  340. // teExam.setInProcessFaceStrangerIgnore(1);
  341. // teExam.setInProcessLivenessVerify(1);
  342. // teExam.setInProcessLivenessIntervalSeconds(30);
  343. // teExam.setInProcessLivenessJudgePolicy(1);
  344. // teExam.setRecordSelectStrategy(1);
  345. // teExam.setEnableIpLimit(1);
  346. // teExam.setIpAllow("1");
  347. // teExam.setScoreStatus(1);
  348. // teExamService.save(teExam);
  349. //
  350. // //考试场次
  351. // TEExamActivity teExamActivity = new TEExamActivity();
  352. // teExamActivity.setId(Constants.idGen.next());
  353. // teExamActivity.setExamId(teExam.getId());
  354. // teExamActivity.setCode(RandomStringUtils.randomAlphanumeric(20));
  355. // teExamActivity.setPrepareSeconds(30);
  356. // teExamActivity.setMaxDurationSeconds(30);
  357. // teExamActivity.setEnable(1);
  358. // teExamActivity.setOpeningSeconds(30);
  359. // teExamActivity.setStartTime(new Date());
  360. // teExamActivity.setFinishTime(new Date());
  361. // teExamActivity.setCreateTime(new Date());
  362. // teExamActivityService.insertInfo(tableName, teExamActivity);
  363. //
  364. // //考试科目
  365. // TEExamCourse teExamCourse = new TEExamCourse();
  366. // teExamCourse.setId(Constants.idGen.next());
  367. // teExamCourse.setExamId(teExam.getId());
  368. // teExamCourse.setCourseCode(RandomStringUtils.randomAlphanumeric(5));
  369. // teExamCourse.setCourseName("测试科目1");
  370. // teExamCourse.setObjectiveShuffle(1);
  371. // teExamCourse.setOptionShuffle(1);
  372. // teExamCourse.setPaperCount(1);
  373. // teExamCourse.setHasAnswer(1);
  374. // teExamCourse.setAudioPlayCount(1);
  375. // teExamCourseService.save(teExamCourse);
  376. //
  377. // //考试试卷
  378. // TEExamPaper teExamPaper = new TEExamPaper();
  379. // teExamPaper.setId(Constants.idGen.next());
  380. // teExamPaper.setName("test1");
  381. // teExamPaper.setTotalScore(100D);
  382. // teExamPaper.setPaperPath("123");
  383. // teExamPaper.setDecryptSecret("345");
  384. // teExamPaper.setEncryptMode(1);
  385. // teExamPaper.setNeedVoiceAnswer(1);
  386. // teExamPaper.setExamId(teExam.getId());
  387. // teExamPaper.setCode("test1");
  388. // teExamPaper.setCourseCode(teExamCourse.getCourseCode());
  389. // teExamPaper.setAnswerPath("123");
  390. // teExamPaper.setHasAudio(1);
  391. // teExamPaper.setWeight(1D);
  392. // teExamPaper.setAudioPlayCount(1);
  393. // teExamPaperService.save(teExamPaper);
  394. //
  395. // //考生
  396. // TEExamStudent teExamStudent = new TEExamStudent();
  397. // teExamStudent.setId(Constants.idGen.next());
  398. // teExamStudent.setExamId(teExam.getId());
  399. // teExamStudent.setExamActivityId(teExamActivity.getId());
  400. // teExamStudent.setStudentId(teStudent.getId());
  401. // teExamStudent.setCourseCode(teExamCourse.getCourseCode());
  402. // teExamStudent.setRoomCode("1");
  403. // teExamStudent.setIdentity(RandomStringUtils.randomAlphanumeric(20));
  404. // teExamStudent.setName("132");
  405. // Map stuMap = new HashMap();
  406. // stuMap.put("examTest1", "aaa");
  407. // stuMap.put("examTest2", "bbb");
  408. // teExamStudent.setParameter(JacksonUtil.parseJson(stuMap));
  409. // teExamStudent.setLeftExamCount(1);
  410. // teExamStudent.setRoomName("test1");
  411. // teExamStudent.setEnable(1);
  412. // teExamStudentService.save(teExamStudent);
  413. //
  414. // //todo
  415. //// Gson gson = new Gson();
  416. //// MTEStudentEntity mteStudentEntity = gson.fromJson(gson.toJson(teStudent), MTEStudentEntity.class);
  417. //// MTEExamEntity mteExamEntity = gson.fromJson(gson.toJson(teExam), MTEExamEntity.class);
  418. //// MTEExamActivityEntity mteExamActivityEntity = gson.fromJson(gson.toJson(teExamActivity), MTEExamActivityEntity.class);
  419. //// MTEExamPaperEntity mteExamPaperEntity = gson.fromJson(gson.toJson(teExamPaper), MTEExamPaperEntity.class);
  420. //// MTEExamCourseEntity mteExamCourseEntity = gson.fromJson(gson.toJson(teExamCourse), MTEExamCourseEntity.class);
  421. //// MTEExamStudentEntity mteExamStudentEntity = gson.fromJson(gson.toJson(teExamStudent), MTEExamStudentEntity.class);
  422. // //todo
  423. //
  424. //// List list = Arrays.asList(mteExamPaperEntity);
  425. //// mteExamCourseEntity.setMteExamPaperEntityList(list);
  426. //
  427. //// list = Arrays.asList(mteExamActivityEntity);
  428. //// mteExamEntity.setMteExamActivityEntityList(list);
  429. //
  430. //// list = Arrays.asList(mteExamCourseEntity);
  431. //// mteExamStudentEntity.setMteExamEntity(mteExamEntity);
  432. //// mteExamStudentEntity.setMteExamActivityEntity(mteExamActivityEntity);
  433. //// mteExamStudentEntity.setMteStudentEntity(mteStudentEntity);
  434. //// mteExamStudentEntity.setMteExamCourseEntityList(list);
  435. //
  436. // //todo
  437. //// mongoTemplate.save(mteStudentEntity);
  438. //// mongoTemplate.save(mteExamEntity);
  439. //// mongoTemplate.save(mteExamActivityEntity);
  440. //// mongoTemplate.save(mteExamPaperEntity);
  441. //// mongoTemplate.save(mteExamCourseEntity);
  442. //// mongoTemplate.save(mteExamStudentEntity);
  443. ////
  444. //// IPage<TEExamActivity> map = teExamActivityService.selectListPage(new Page<>(0, 10), tableName);
  445. //// log.info("mysql map:{}", JacksonUtil.parseJson(map));
  446. ////
  447. //// Query query = new Query();
  448. ////// query.addCriteria(Criteria.where("questionId").in(setQuestionId).andOperator(Criteria.where("examRecordDataId").is(examSessionInfo.getExamRecordDataId())));
  449. //// query.skip((1 - 1) * 10).limit(10);//设置起始数和查询条数
  450. //// List<MTEStudentEntity> mteStudentEntityList = mongoTemplate.find(query, MTEStudentEntity.class);
  451. //// log.info("mongodb mteStudentEntityList:{}", JacksonUtil.parseJson(mteStudentEntityList));
  452. ////// List<MTEStudentEntity> mteStudentEntityList = mongoTemplate.findAll(MTEStudentEntity.class);
  453. ////// log.info("mongodb mteStudentEntityList:{}", JacksonUtil.parseJson(mteStudentEntityList));
  454. ////
  455. //// List<MTEExamEntity> mteExamEntityList = mongoTemplate.findAll(MTEExamEntity.class);
  456. //// log.info("mongodb mteExamEntityList:{}", JacksonUtil.parseJson(mteExamEntityList));
  457. ////
  458. //// List<MTEExamActivityEntity> mteExamActivityEntityList = mongoTemplate.findAll(MTEExamActivityEntity.class);
  459. //// log.info("mongodb mteExamActivityEntityList:{}", JacksonUtil.parseJson(mteExamActivityEntityList));
  460. ////// List<TEExamActivity> ps = new ArrayList<>();
  461. ////// mteExamActivityEntityList.forEach(s -> {
  462. ////// TEExamActivity t = gson.fromJson(gson.toJson(s), TEExamActivity.class);
  463. ////// ps.add(t);
  464. ////// });
  465. //////// List<TEExamActivity> ps = gson.fromJson(JacksonUtil.parseJson(mteExamActivityEntityList), new TypeToken<List<TEExamActivity>>(){}.getType());
  466. ////// map.setRecords(ps);
  467. ////
  468. //// List<MTEExamPaperEntity> mteExamPaperEntityList = mongoTemplate.findAll(MTEExamPaperEntity.class);
  469. //// log.info("mongodb mteExamPaperEntityList:{}", JacksonUtil.parseJson(mteExamPaperEntityList));
  470. ////
  471. //// List<MTEExamCourseEntity> mteExamCourseEntityList = mongoTemplate.findAll(MTEExamCourseEntity.class);
  472. //// log.info("mongodb mteExamCourseEntityList:{}", JacksonUtil.parseJson(mteExamCourseEntityList));
  473. ////
  474. //// List<MTEExamStudentEntity> mteExamStudentEntityList = mongoTemplate.findAll(MTEExamStudentEntity.class);
  475. //// log.info("mongodb mteExamStudentEntityList:{}", JacksonUtil.parseJson(mteExamStudentEntityList));
  476. //// List<TEExamStudent> ps = new ArrayList<>();
  477. //// mteExamStudentEntityList.forEach(s -> {
  478. //// TEExamStudent t = gson.fromJson(gson.toJson(s), TEExamStudent.class);
  479. //// ps.add(t);
  480. //// });
  481. //// List<MTEExamStudentEntity> ps1 = new ArrayList<>();
  482. //// List<TEExamStudent> list1 = teExamStudentService.list();
  483. //// list1.forEach(s -> {
  484. //// MTEExamStudentEntity t = gson.fromJson(gson.toJson(s), MTEExamStudentEntity.class);
  485. //// ps1.add(t);
  486. //// });
  487. // //todo
  488. //// teExamActivityService.dropTable(tableName);
  489. // return ResultUtil.ok(SystemConstant.SUCCESS);
  490. // }
  491. @ApiOperation(value = "登出接口")
  492. @RequestMapping(value = "/logout", method = RequestMethod.POST)
  493. @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
  494. public Result logout() throws NoSuchAlgorithmException {
  495. TBUser tbUser = (TBUser) ServletUtil.getRequestAccount();
  496. TBSession tbSession = (TBSession) ServletUtil.getRequestSession();
  497. AuthDto authDto = (AuthDto) redisUtil.get(SystemConstant.userOauth + "::" + tbUser.getId());
  498. if (Objects.isNull(tbSession)) {
  499. throw new BusinessException(ExceptionResultEnum.LOGIN_NO);
  500. }
  501. redisUtil.deleteUserSession(tbSession.getId());
  502. //循环检查该用户下其他平台是否存在session,不存在则删除用户缓存和鉴权缓存
  503. boolean delete = true;
  504. for (Source s : Source.values()) {
  505. String sessionId = SessionUtil.digest(tbUser.getId(), Math.abs(authDto.getRoleCodes().toString().hashCode()), s.name());
  506. if (Objects.nonNull(redisUtil.getUserSession(sessionId))) {
  507. delete = false;
  508. break;
  509. }
  510. }
  511. if (delete) {
  512. redisUtil.deleteUser(tbUser.getId());
  513. cacheService.removeAccountCache(tbUser.getId());
  514. }
  515. //mq发送消息start
  516. MqDto mqDto = new MqDto(MqTopicEnum.THEMIS_TOPIC.getCode(), MqTagEnum.USER.name(), SystemOperationEnum.LOGOUT, MqTagEnum.USER, String.valueOf(tbUser.getId()), tbUser.getLoginName());
  517. mqDtoService.assembleSendOneWayMsg(mqDto);
  518. //mq发送消息end
  519. return ResultUtil.ok(Collections.singletonMap(SystemConstant.SUCCESS, true));
  520. }
  521. // @CachePut(value = "user_cache", key = "'userCacheQuery'")
  522. @ApiOperation(value = "用户查询接口")
  523. @RequestMapping(value = "/query", method = RequestMethod.POST)
  524. @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = TBUserDto.class)})
  525. public Result query(@ApiParam(value = "用户id", required = false) @RequestParam(required = false) Long id, @ApiParam(value = "登录名", required = false) @RequestParam(required = false) String loginName, @ApiParam(value = "姓名", required = false) @RequestParam(required = false) String name, @ApiParam(value = "角色", required = false) @RequestParam(required = false) String roleCode, @ApiParam(value = "是否启用", required = false) @RequestParam(required = false) Integer enable, @ApiParam(value = "分页页码", required = true) @RequestParam int pageNumber, @ApiParam(value = "分页数", required = true) @RequestParam int pageSize) {
  526. IPage<TBUserDto> tbUserIPage = tbUserService.userQuery(new Page<>(pageNumber, pageSize), id, loginName, name, roleCode, enable);
  527. tbUserIPage.getRecords().forEach(s -> {
  528. if (Objects.nonNull(s.getRoleNameStr())) {
  529. s.setRoleName(Arrays.asList(s.getRoleNameStr().split(",")));
  530. }
  531. if (Objects.nonNull(s.getRoleCodeStr())) {
  532. s.setRoleCode(Arrays.asList(s.getRoleCodeStr().split(",")));
  533. }
  534. });
  535. return ResultUtil.ok(tbUserIPage);
  536. }
  537. // @CacheEvict(value = "user_cache", key = "'userCacheQuery'")
  538. @ApiOperation(value = "用户新增/编辑接口")
  539. @RequestMapping(value = "/save", method = RequestMethod.POST)
  540. @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
  541. @Transactional
  542. public Result save(@ApiJsonObject(name = "userSave", value = {
  543. @ApiJsonProperty(key = "id", type = "long", example = "1", description = "新增不需要主键"),
  544. @ApiJsonProperty(key = "orgId", example = "1", description = "机构id"),
  545. @ApiJsonProperty(key = "loginName", description = "登录名,新增必须"),
  546. @ApiJsonProperty(key = "name", description = "姓名,新增必须"),
  547. @ApiJsonProperty(key = "password", description = "密码,新增必须"),
  548. @ApiJsonProperty(key = "enable", type = "int", example = "1", description = "是否启用"),
  549. @ApiJsonProperty(key = "mobileNumber", description = "手机号"),
  550. @ApiJsonProperty(key = "roleCode", description = "角色")
  551. }) @ApiParam(value = "用户信息", required = true) @RequestBody Map<String, Object> mapParameter) {
  552. if (Objects.isNull(mapParameter)) {
  553. throw new BusinessException(ExceptionResultEnum.USER_INFO_IS_NULL);
  554. }
  555. if (Objects.isNull(mapParameter.get("orgId"))) {
  556. throw new BusinessException(ExceptionResultEnum.ORG_ID_IS_NULL);
  557. }
  558. TBUser loginUser = (TBUser) ServletUtil.getRequestAccount();
  559. Long orgId = Long.parseLong(String.valueOf(mapParameter.get("orgId")));
  560. try {
  561. Gson gson = new Gson();
  562. TBUser tbUser = gson.fromJson(gson.toJson(mapParameter), TBUser.class);
  563. List<String> roleList = (List<String>) mapParameter.get("roleCode");
  564. if (Objects.isNull(roleList) || roleList.size() == 0) {
  565. throw new BusinessException("请选择角色");
  566. }
  567. Set<String> roleSet = new HashSet<>(roleList);
  568. if (roleSet.size() > 1) {
  569. throw new BusinessException("暂不支持多个角色");
  570. }
  571. if (Objects.isNull(tbUser.getId())) {
  572. tbUser.setId(Constants.idGen.next());
  573. tbUser.setOrgId(orgId);
  574. tbUser.setCreateId(loginUser.getId());
  575. if (Objects.nonNull(roleSet) && roleSet.size() > 0) {
  576. TBUser finalTbUser = tbUser;
  577. roleSet.forEach(s -> {
  578. TBUserRole tbUserRole = new TBUserRole(finalTbUser.getId(), s);
  579. tbUserRoleService.save(tbUserRole);
  580. });
  581. }
  582. } else {
  583. if (Objects.nonNull(roleSet) && roleSet.size() > 0) {
  584. QueryWrapper<TBUserRole> tbUserRoleQueryWrapper = new QueryWrapper<>();
  585. tbUserRoleQueryWrapper.lambda().eq(TBUserRole::getUserId, tbUser.getId());
  586. tbUserRoleService.remove(tbUserRoleQueryWrapper);
  587. TBUser finalTbUser1 = tbUser;
  588. roleSet.forEach(s -> {
  589. TBUserRole tbUserRole = new TBUserRole(finalTbUser1.getId(), s);
  590. tbUserRoleService.save(tbUserRole);
  591. });
  592. }
  593. tbUser.setUpdateId(loginUser.getId());
  594. }
  595. tbUserService.saveOrUpdate(tbUser);
  596. //清除用户缓存
  597. if (Objects.nonNull(roleSet) && roleSet.size() > 0) {
  598. AuthDto authDto = (AuthDto) redisUtil.get(SystemConstant.userOauth + "::" + tbUser.getId());
  599. if (Objects.nonNull(authDto)) {
  600. for (Source s : Source.values()) {
  601. String sessionId = SessionUtil.digest(tbUser.getId(), Math.abs(authDto.getRoleCodes().toString().hashCode()), s.name());
  602. redisUtil.deleteUserSession(sessionId);
  603. }
  604. }
  605. redisUtil.deleteUser(tbUser.getId());
  606. cacheService.removeAccountCache(tbUser.getId());
  607. }
  608. } catch (Exception e) {
  609. log.error("请求出错", e);
  610. if (e instanceof DuplicateKeyException) {
  611. String errorColumn = e.getCause().toString();
  612. String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
  613. throw new BusinessException("机构id[" + orgId + "]下的" + FieldUniqueEnum.convertToCode(columnStr) + "数据不允许重复插入");
  614. } else if (e instanceof BusinessException) {
  615. throw new BusinessException(e.getMessage());
  616. } else {
  617. throw new RuntimeException(e);
  618. }
  619. }
  620. return ResultUtil.ok(Collections.singletonMap(SystemConstant.SUCCESS, true));
  621. }
  622. @ApiOperation(value = "获取短信验证码接口")
  623. @RequestMapping(value = "/getVerifyCode", method = RequestMethod.POST)
  624. @ApiResponses({@ApiResponse(code = 200, message = "{\"verifyCode\":123456}", response = Result.class)})
  625. public Result getVerifyCode(@ApiParam(value = "登录名", required = true) @RequestParam String loginName) {
  626. if (Objects.isNull(loginName) || Objects.equals(loginName, "")) {
  627. throw new BusinessException(ExceptionResultEnum.LOGIN_NAME_IS_NULL);
  628. }
  629. Map map = new HashMap();
  630. return ResultUtil.ok(map);
  631. }
  632. @ApiOperation(value = "获取短信验证码接口")
  633. @RequestMapping(value = "/validate/verifyCode", method = RequestMethod.POST)
  634. @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
  635. public Result validateVerifyCode(@ApiParam(value = "验证码", required = true) @RequestParam String verifyCode) {
  636. if (Objects.isNull(verifyCode) || Objects.equals(verifyCode, "")) {
  637. throw new BusinessException(ExceptionResultEnum.VERIFYCODE_IS_NULL);
  638. }
  639. return ResultUtil.ok(Collections.singletonMap(SystemConstant.SUCCESS, true));
  640. }
  641. @ApiOperation(value = "二次验证获取短信验证码接口")
  642. @RequestMapping(value = "/validate/getVerifyCode", method = RequestMethod.POST)
  643. @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
  644. public Result validateGetVerifyCode() {
  645. return ResultUtil.ok(Collections.singletonMap(SystemConstant.SUCCESS, true));
  646. }
  647. @ApiOperation(value = "用户停用/启用接口")
  648. @RequestMapping(value = "/enable", method = RequestMethod.POST)
  649. @Transactional
  650. @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
  651. public Result enableUser(@ApiJsonObject(name = "enableUser", value = {
  652. @ApiJsonProperty(key = "id", type = "long", example = "1", description = "用户id"),
  653. @ApiJsonProperty(key = "enable", type = "int", example = "1", description = "停用/启用")
  654. }) @ApiParam(value = "用户信息", required = true) @RequestBody Map<String, Object> user) {
  655. if (Objects.isNull(user.get("id")) || Objects.equals(user.get("id"), "")) {
  656. throw new BusinessException(ExceptionResultEnum.USER_ID_IS_NULL);
  657. }
  658. Long userId = Long.parseLong(String.valueOf(user.get("id")));
  659. if (Objects.isNull(user.get("enable")) || Objects.equals(user.get("enable"), "")) {
  660. throw new BusinessException(ExceptionResultEnum.ENABLE_IS_NULL);
  661. }
  662. Integer enable = Integer.parseInt(String.valueOf(user.get("enable")));
  663. TBUser tbUser = tbUserService.getById(userId);
  664. if (Objects.isNull(tbUser)) {
  665. throw new BusinessException(ExceptionResultEnum.USER_NO);
  666. }
  667. //保存用户
  668. tbUser.setEnable(enable);
  669. tbUserService.updateById(tbUser);
  670. redisUtil.setUser(tbUser.getId(), tbUser);
  671. return ResultUtil.ok(Collections.singletonMap(SystemConstant.SUCCESS, true));
  672. }
  673. @ApiOperation(value = "用户修改密码接口")
  674. @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
  675. @ApiResponses({@ApiResponse(code = 200, message = "{\"success\":true}", response = Result.class)})
  676. @Transactional
  677. public Result userUpdatePwd(@ApiJsonObject(name = "userUpdatePwd", value = {
  678. @ApiJsonProperty(key = "id", type = "long", example = "1", description = "用户ID"),
  679. @ApiJsonProperty(key = "password", description = "新密码")
  680. }) @ApiParam(value = "用户信息", required = true) @RequestBody Map<String, Object> mapParameter) {
  681. if (Objects.isNull(mapParameter.get("id")) || Objects.equals(mapParameter.get("id"), "")) {
  682. throw new BusinessException(ExceptionResultEnum.USER_ID_IS_NULL);
  683. }
  684. Long id = Long.parseLong(String.valueOf(mapParameter.get("id")));
  685. if (Objects.isNull(mapParameter.get("password")) || Objects.equals(mapParameter.get("password"), "")) {
  686. throw new BusinessException(ExceptionResultEnum.PASSWORD_IS_NULL);
  687. }
  688. String password = String.valueOf(mapParameter.get("password"));
  689. TBUser tbUser = tbUserService.getById(id);
  690. if (Objects.isNull(tbUser)) {
  691. throw new BusinessException(ExceptionResultEnum.USER_NO);
  692. }
  693. TBUser currentUser = (TBUser) ServletUtil.getRequestAccount();
  694. tbUser.setPassword(password);
  695. tbUser.setUpdateId(currentUser.getId());
  696. tbUserService.updateById(tbUser);
  697. redisUtil.deleteUser(tbUser.getId());
  698. return ResultUtil.ok(Collections.singletonMap(SystemConstant.SUCCESS, true));
  699. }
  700. }