UserController.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package com.izouma.nineth.web;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alipay.api.AlipayApiException;
  4. import com.fasterxml.jackson.annotation.JsonView;
  5. import com.huifu.adapay.core.exception.BaseAdaPayException;
  6. import com.izouma.nineth.converter.EncryptConverter;
  7. import com.izouma.nineth.domain.Follow;
  8. import com.izouma.nineth.domain.IdentityAuth;
  9. import com.izouma.nineth.domain.User;
  10. import com.izouma.nineth.dto.*;
  11. import com.izouma.nineth.enums.AuthorityName;
  12. import com.izouma.nineth.exception.BusinessException;
  13. import com.izouma.nineth.repo.*;
  14. import com.izouma.nineth.security.Authority;
  15. import com.izouma.nineth.security.JwtTokenUtil;
  16. import com.izouma.nineth.security.JwtUserFactory;
  17. import com.izouma.nineth.service.FollowService;
  18. import com.izouma.nineth.service.UserBankCardService;
  19. import com.izouma.nineth.service.UserService;
  20. import com.izouma.nineth.utils.SecurityUtils;
  21. import com.izouma.nineth.utils.excel.ExcelUtils;
  22. import io.swagger.annotations.ApiOperation;
  23. import lombok.AllArgsConstructor;
  24. import me.chanjar.weixin.common.error.WxErrorException;
  25. import org.apache.commons.collections.CollectionUtils;
  26. import org.apache.commons.lang3.ObjectUtils;
  27. import org.apache.commons.lang3.StringUtils;
  28. import org.springframework.data.domain.Page;
  29. import org.springframework.data.redis.core.RedisTemplate;
  30. import org.springframework.security.access.prepost.PreAuthorize;
  31. import org.springframework.web.bind.annotation.*;
  32. import javax.servlet.http.HttpServletResponse;
  33. import java.io.IOException;
  34. import java.time.LocalDateTime;
  35. import java.util.*;
  36. @AllArgsConstructor
  37. @RestController
  38. @RequestMapping("/user")
  39. public class UserController extends BaseController {
  40. private UserRepo userRepo;
  41. private UserService userService;
  42. private JwtTokenUtil jwtTokenUtil;
  43. private FollowService followService;
  44. private UserBankCardRepo userBankCardRepo;
  45. private RedisTemplate<String, Object> redisTemplate;
  46. private UserBankCardService userBankCardService;
  47. private IdentityAuthRepo identityAuthRepo;
  48. private TokenHistoryRepo tokenHistoryRepo;
  49. private FollowRepo followRepo;
  50. @PostMapping("/register")
  51. public User register(@RequestParam String username,
  52. @RequestParam String password) {
  53. UserRegister user = UserRegister.builder()
  54. .username(username)
  55. .nickname(username)
  56. .password(password)
  57. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  58. .build();
  59. return userService.create(user);
  60. }
  61. @PreAuthorize("hasAnyRole('ADMIN', 'SHOWROOM','SAAS')")
  62. @PostMapping("/create")
  63. public User create(@RequestBody UserRegister userRegister) {
  64. return userService.create(userRegister);
  65. }
  66. @PreAuthorize("hasAnyRole('ADMIN', 'SHOWROOM')")
  67. @PostMapping("/save")
  68. public User save(@RequestBody User user) {
  69. if (user.getId() != null) {
  70. return userService.update(user);
  71. }
  72. return userService.save(user);
  73. }
  74. @PostMapping("/update")
  75. public User update(String nickname, String avatar, String sex, String bg, String intro,
  76. Boolean useCollectionPic, Boolean riskWarning, Integer level, Boolean isPublicShow) {
  77. return userService.update(SecurityUtils.getAuthenticatedUser().getId(),
  78. nickname, avatar, sex, bg, intro, useCollectionPic, riskWarning, level, isPublicShow);
  79. }
  80. @GetMapping("/my")
  81. public User my(@RequestParam(defaultValue = "false") boolean refresh) {
  82. if (refresh) {
  83. redisTemplate.delete("myUserInfo::" + SecurityUtils.getAuthenticatedUser().getId());
  84. }
  85. return userService.my(SecurityUtils.getAuthenticatedUser().getId());
  86. }
  87. @GetMapping("/myAdmin")
  88. @PreAuthorize("hasRole('ADMIN')")
  89. public User myAdmin() {
  90. return userRepo.findById(SecurityUtils.getAuthenticatedUser().getId())
  91. .orElseThrow(new BusinessException("用户不存在"));
  92. }
  93. @GetMapping("/myTrading")
  94. public Object myTrading(@RequestParam(defaultValue = "false") boolean refresh) {
  95. if (refresh) {
  96. redisTemplate.delete("myUserInfo::" + SecurityUtils.getAuthenticatedUser().getId());
  97. }
  98. return userService.myTrading(SecurityUtils.getAuthenticatedUser().getId());
  99. }
  100. // @PreAuthorize("hasRole('ADMIN')")
  101. @PostMapping("/all")
  102. public Page<UserDTO> all(@RequestBody PageQuery pageQuery) {
  103. pageQuery.getQuery().put("minter", true);
  104. pageQuery.getQuery().putIfAbsent("companyId", 1L);
  105. if (pageQuery.getSize() > 100) pageQuery.setSize(100);
  106. return userService.toDTO(userService.all(pageQuery).toPage());
  107. }
  108. @PreAuthorize("hasAnyRole('ADMIN', 'SHOWROOM')")
  109. @PostMapping("/adminAll")
  110. public Page<User> adminAll(@RequestBody PageQuery pageQuery) {
  111. return userService.all(pageQuery).toPage();
  112. }
  113. @PostMapping("/minterList")
  114. public Page<Minter> toMinter(@RequestBody PageQuery pageQuery) {
  115. pageQuery.getQuery().put("minter", true);
  116. return userService.toMinterDTO(userService.all(pageQuery).toPage());
  117. }
  118. // @PreAuthorize("hasRole('ADMIN')")
  119. @GetMapping("/get/{id}")
  120. public UserDTO get(@PathVariable Long id) {
  121. return userService.toDTO(userRepo.findById(id).orElseThrow(new BusinessException("无记录")), true);
  122. }
  123. @PreAuthorize("hasRole('ADMIN')")
  124. @GetMapping("/adminGet/{id}")
  125. @JsonView(User.View.Detail.class)
  126. public User adminGet(@PathVariable Long id) {
  127. return userRepo.findById(id).orElseThrow(new BusinessException("无记录"));
  128. }
  129. @PreAuthorize("hasRole('ADMIN')")
  130. @PostMapping("/del/{id}")
  131. public void del(@PathVariable Long id) {
  132. userService.del(id);
  133. }
  134. @GetMapping("/excel")
  135. @ResponseBody
  136. public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
  137. List<User> data = userService.all(pageQuery).getContent();
  138. ExcelUtils.export(response, data);
  139. }
  140. @PostMapping("/getMaUserInfo")
  141. @ApiOperation(value = "获取小程序用户信息")
  142. public User getMaUserInfo(String sessionKey, String rawData, String signature, String encryptedData, String iv) {
  143. User user = userService.getMaUserInfo(sessionKey, rawData, signature, encryptedData, iv);
  144. if (user != null) {
  145. return user;
  146. }
  147. throw new BusinessException("获取用户信息失败");
  148. }
  149. @PostMapping("/code2openId")
  150. @ApiOperation(value = "获取OpenId")
  151. public String code2openId(@RequestParam String code) throws WxErrorException {
  152. return userService.code2openId(code);
  153. }
  154. @PreAuthorize("hasRole('ADMIN')")
  155. @PostMapping("/setPasswordAdmin")
  156. public String setPasswordAdmin(@RequestParam Long userId, @RequestParam String password) {
  157. return userService.setPassword(userId, password);
  158. }
  159. @PostMapping("/changePassword")
  160. @ApiOperation("修改密码")
  161. public String changePassword(@RequestParam String password, @RequestParam String code) {
  162. return userService.setPassword(SecurityUtils.getAuthenticatedUser().getId(), code, password);
  163. }
  164. @PostMapping("/forgotPassword")
  165. @ApiOperation("忘记密码")
  166. public String forgotPassword(@RequestParam String phone, @RequestParam String password, @RequestParam String code) {
  167. return userService.forgotPassword(phone, password, code);
  168. }
  169. @PreAuthorize("hasRole('ADMIN')")
  170. @GetMapping("/getToken/{userId}")
  171. public String getToken(@PathVariable Long userId) {
  172. return jwtTokenUtil.generateToken(JwtUserFactory.create(userRepo.findById(userId)
  173. .orElseThrow(new BusinessException("用户不存在"))));
  174. }
  175. @PostMapping("/bindPhone")
  176. public void bindPhone(@RequestParam String phone) {
  177. userService.bindPhone(SecurityUtils.getAuthenticatedUser().getId(), phone);
  178. }
  179. @GetMapping("/{id}/follow")
  180. public void follow(@PathVariable Long id) {
  181. followService.follow(SecurityUtils.getAuthenticatedUser().getId(), id);
  182. }
  183. @GetMapping("/{id}/unfollow")
  184. public void unfollow(@PathVariable Long id) {
  185. followService.unfollow(SecurityUtils.getAuthenticatedUser().getId(), id);
  186. }
  187. @GetMapping("/myFollows")
  188. @ApiOperation("我的关注")
  189. public List<UserDTO> myFollows() {
  190. return userService.toDTO(userRepo.userFollows(SecurityUtils.getAuthenticatedUser().getId()));
  191. }
  192. @GetMapping("/myFollowers")
  193. @ApiOperation("关注我的")
  194. public List<UserDTO> myFollowers() {
  195. return userService.toDTO(userRepo.userFollowers(SecurityUtils.getAuthenticatedUser().getId()));
  196. }
  197. @PostMapping("/setTradeCode")
  198. @ApiOperation("修改交易密码")
  199. public void setTradeCode(@RequestParam String token, @RequestParam String tradeCode) {
  200. userService.setTradeCode(SecurityUtils.getAuthenticatedUser().getId(), token, tradeCode);
  201. }
  202. @PostMapping("/verifyTradeCode")
  203. @ApiOperation("验证交易密码")
  204. public void verifyTradeCode(@RequestParam String tradeCode) {
  205. userService.verifyTradeCode(SecurityUtils.getAuthenticatedUser().getId(), tradeCode);
  206. }
  207. @PostMapping("/searchByPhone")
  208. public Map<String, Object> searchByPhone(@RequestParam String phone) {
  209. return userService.searchByPhone(phone);
  210. }
  211. @PreAuthorize("hasAnyRole('ADMIN', 'OPERATOR', 'SAAS')")
  212. @PostMapping("/searchByPhoneAdmin")
  213. public Map<String, Object> searchByPhoneAdmin(@RequestParam String phone) {
  214. return userService.searchByPhoneAdmin(phone);
  215. }
  216. @GetMapping("/tradeCodeStatus")
  217. public Object tradeCodeStatus() {
  218. return new HashMap<String, Object>() {{
  219. put("set", StringUtils.isNotBlank(
  220. userRepo.findById(SecurityUtils.getAuthenticatedUser().getId()).map(User::getTradeCode).orElse(null)
  221. ));
  222. }};
  223. }
  224. @GetMapping("/myBankCard")
  225. public List<UserBankCard> myBankCard() {
  226. return userBankCardRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId());
  227. }
  228. @PostMapping("/addBankCard")
  229. public void addBankCard(@RequestParam String bankNo, @RequestParam String phone, @RequestParam String code) throws BaseAdaPayException {
  230. userService.addBankCard(SecurityUtils.getAuthenticatedUser().getId(), bankNo, phone, code);
  231. }
  232. @PostMapping("/removeBankCard")
  233. public void removeBankCard() throws BaseAdaPayException {
  234. userService.removeBankCard(SecurityUtils.getAuthenticatedUser().getId());
  235. }
  236. @PostMapping("/removeBankCardAdmin")
  237. @PreAuthorize("hasAnyRole('ADMIN')")
  238. public void removeBankCardAdmin(@RequestParam Long userId) throws BaseAdaPayException {
  239. userService.removeBankCard(userId);
  240. }
  241. @PostMapping("/removeAuthAdmin")
  242. @PreAuthorize("hasAnyRole('ADMIN')")
  243. public void removeAuthAdmin(@RequestParam Long userId) {
  244. userService.removeAuth(userId);
  245. }
  246. @PreAuthorize("hasAnyRole('ADMIN')")
  247. @PostMapping("/batchRegister")
  248. public Map<String, Object> batchRegister(@RequestParam String phones, @RequestParam String defaultPassword) {
  249. return userService.batchRegister(phones, defaultPassword);
  250. }
  251. @PreAuthorize("hasAnyRole('ADMIN')")
  252. @PostMapping("/exportInvite")
  253. @ResponseBody
  254. public void exportInvite(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
  255. // List<InvitePhoneDTO> data = userService.all(pageQuery)
  256. // .map(InvitePhoneDTO::new)
  257. // .getContent();
  258. Page<InvitePhoneDTO> user = (Page<InvitePhoneDTO>) this.invite(pageQuery).get("user");
  259. ExcelUtils.export(response, user.getContent());
  260. }
  261. @PostMapping("/invite")
  262. public Map<String, Object> invite(@RequestBody PageQuery pageQuery) {
  263. return userService.invite(pageQuery);
  264. }
  265. @GetMapping("/collectionInvite")
  266. public List<User> collectionInvite(@RequestParam Long collectionId) {
  267. return userRepo.findAllByCollectionIdAndCollectionInvitorAndSettleAccountIdIsNotNull(collectionId,
  268. SecurityUtils.getAuthenticatedUser().getId());
  269. }
  270. @PreAuthorize("hasAnyRole('ADMIN')")
  271. @GetMapping("/checkSettleAccount")
  272. public String checkSettleAccount() {
  273. userService.checkSettleAccountAsync();
  274. return "ok";
  275. }
  276. @PreAuthorize("hasAnyRole('ADMIN')")
  277. @GetMapping("/scanWeakPass")
  278. public String scanWeakPass() {
  279. userService.scanWeakPassword();
  280. return "ok";
  281. }
  282. @PostMapping("/collectionInvitorList")
  283. public List<InvitorDTO> invitorList(@RequestParam Long collectionId) {
  284. return userService.findInviteOrderByCount(collectionId);
  285. }
  286. @PostMapping("/findMyInviteRecord")
  287. public InvitorDetailDTO invitorList(@RequestParam Long collectionId, @RequestParam Long userId) {
  288. return userService.findMyInviteRecord(userId, collectionId);
  289. }
  290. @PostMapping("/enableWallet")
  291. public void enableWallet() {
  292. userService.enableWallet(SecurityUtils.getAuthenticatedUser().getId());
  293. }
  294. @PreAuthorize("hasAnyRole('ADMIN', 'SHOWROOM')")
  295. @PostMapping("/companyAll")
  296. public Page<CompanyDTO> companyAll(@RequestBody PageQuery pageQuery) {
  297. return userService.companyList(pageQuery);
  298. }
  299. @PostMapping("/faceAuth")
  300. public Map<String, String> faceAuth(@RequestParam String name, @RequestParam String idNo) throws AlipayApiException {
  301. String certifyId = userService.prepareAliAuth("IDENTITY_CARD",
  302. SecurityUtils.getAuthenticatedUser().getId(), name, idNo);
  303. String url = userService.getAliAuthUrl(certifyId);
  304. Map<String, String> map = new HashMap<>();
  305. map.put("certifyId", certifyId);
  306. map.put("url", url);
  307. return map;
  308. }
  309. @GetMapping("/checkFaceAuth")
  310. public Map<String, Object> checkFaceAuth(@RequestParam String certifyId) throws AlipayApiException {
  311. return userService.checkFaceAuth(certifyId);
  312. }
  313. @GetMapping(value = "/faceAuthNotify/{id}", produces = "text/html")
  314. public String faceAuthNotify(@PathVariable Long id) {
  315. userService.faceAuthNotify(id);
  316. return "<!DOCTYPE html>\n" +
  317. "<html lang=\"en\">\n" +
  318. "\n" +
  319. "<head>\n" +
  320. " <meta charset=\"UTF-8\">\n" +
  321. " <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
  322. " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
  323. " <title>认证完成</title>\n" +
  324. "</head>\n" +
  325. "\n" +
  326. "<body>\n" +
  327. " <script>\n" +
  328. " function ready(callback) {\n" +
  329. " // 如果jsbridge已经注入则直接调用\n" +
  330. " if (window.AlipayJSBridge) {\n" +
  331. " callback && callback();\n" +
  332. " } else {\n" +
  333. " // 如果没有注入则监听注入的事件\n" +
  334. " document.addEventListener('AlipayJSBridgeReady', callback, false);\n" +
  335. " }\n" +
  336. " }\n" +
  337. " ready(function () {\n" +
  338. " AlipayJSBridge.call('exitApp');\n" +
  339. " });\n" +
  340. " </script>\n" +
  341. "</body>\n" +
  342. "\n" +
  343. "</html>";
  344. }
  345. @PostMapping("synchronizationData")
  346. public UserSynchronizationDto synchronizationData(@RequestBody String phone) {
  347. User user = userRepo.findByPhoneAndDelFalse(phone).orElse(null);
  348. if (ObjectUtils.isEmpty(user)) {
  349. return null;
  350. }
  351. UserSynchronizationDto dto = new UserSynchronizationDto();
  352. //昵称
  353. dto.setNickname(user.getNickname());
  354. //手机号
  355. dto.setPhone(user.getPhone());
  356. //银行卡
  357. EncryptConverter converter = new EncryptConverter();
  358. List<UserBankCard> byUserId = userBankCardRepo.findByUserId(user.getId());
  359. if (CollectionUtils.isNotEmpty(byUserId)) {
  360. dto.setIsUserBankCard(true);
  361. String bankNo = converter.convertToEntityAttribute(byUserId.get(0).getBankNo());
  362. dto.setBankNo(bankNo);
  363. } else {
  364. dto.setIsUserBankCard(false);
  365. }
  366. //实名
  367. if (ObjectUtils.isNotEmpty(user.getAuthId())) {
  368. IdentityAuth identityAuth = identityAuthRepo.findByIdAndDelFalse(user.getAuthId()).orElse(null);
  369. if (ObjectUtils.isNotEmpty(identityAuth)) {
  370. String idNo = converter.convertToEntityAttribute(identityAuth.getIdNo());
  371. dto.setRealName(identityAuth.getRealName());
  372. dto.setIdNo(idNo);
  373. }
  374. }
  375. dto.setAuthStatus(user.getAuthStatus());
  376. return dto;
  377. }
  378. @GetMapping("/topTen")
  379. public List<User> topTen() {
  380. LocalDateTime time = LocalDateTime.now().plusDays(-7);
  381. List<Map<String, String>> map = tokenHistoryRepo.top(time);
  382. JSONArray jsonArray = new JSONArray();
  383. jsonArray.addAll(map);
  384. List<User> users = jsonArray.toJavaList(User.class);
  385. if (Objects.isNull(SecurityUtils.getAuthenticatedUser())) {
  386. return users;
  387. }
  388. if (CollectionUtils.isEmpty(users)) {
  389. return users;
  390. }
  391. Long id = SecurityUtils.getAuthenticatedUser().getId();
  392. users.forEach(user -> {
  393. List<Follow> follows = followRepo.findByUserIdAndFollowUserId(id, user.getId());
  394. if (CollectionUtils.isNotEmpty(follows)) {
  395. user.setFollow(true);
  396. }
  397. });
  398. return users;
  399. }
  400. @GetMapping("/websocket/{userId}")
  401. public WebsocketUser websocket(@PathVariable Long userId) {
  402. User user = userRepo.findById(userId).orElseThrow(new BusinessException("没有玩家信息"));
  403. return WebsocketUser.create(user);
  404. }
  405. }