UserService.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. package com.izouma.nineth.service;
  2. import cn.binarywang.wx.miniapp.api.WxMaService;
  3. import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
  4. import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
  5. import com.huifu.adapay.core.exception.BaseAdaPayException;
  6. import com.izouma.nineth.config.Constants;
  7. import com.izouma.nineth.domain.Follow;
  8. import com.izouma.nineth.domain.IdentityAuth;
  9. import com.izouma.nineth.domain.Invite;
  10. import com.izouma.nineth.domain.User;
  11. import com.izouma.nineth.dto.*;
  12. import com.izouma.nineth.enums.AuthStatus;
  13. import com.izouma.nineth.enums.AuthorityName;
  14. import com.izouma.nineth.exception.BusinessException;
  15. import com.izouma.nineth.repo.*;
  16. import com.izouma.nineth.security.Authority;
  17. import com.izouma.nineth.security.JwtTokenUtil;
  18. import com.izouma.nineth.security.JwtUserFactory;
  19. import com.izouma.nineth.service.sms.SmsService;
  20. import com.izouma.nineth.service.storage.StorageService;
  21. import com.izouma.nineth.utils.BankUtils;
  22. import com.izouma.nineth.utils.JpaUtils;
  23. import com.izouma.nineth.utils.ObjUtils;
  24. import com.izouma.nineth.utils.SecurityUtils;
  25. import lombok.AllArgsConstructor;
  26. import lombok.extern.slf4j.Slf4j;
  27. import me.chanjar.weixin.common.error.WxErrorException;
  28. import me.chanjar.weixin.mp.api.WxMpService;
  29. import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
  30. import me.chanjar.weixin.mp.bean.result.WxMpUser;
  31. import org.apache.commons.lang3.RandomStringUtils;
  32. import org.apache.commons.lang3.StringUtils;
  33. import org.springframework.beans.BeanUtils;
  34. import org.springframework.cache.annotation.CacheEvict;
  35. import org.springframework.data.domain.Page;
  36. import org.springframework.data.domain.PageImpl;
  37. import org.springframework.data.jpa.domain.Specification;
  38. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  39. import org.springframework.stereotype.Service;
  40. import javax.persistence.criteria.Predicate;
  41. import java.text.SimpleDateFormat;
  42. import java.util.*;
  43. import java.util.regex.Pattern;
  44. import java.util.stream.Collectors;
  45. @Service
  46. @Slf4j
  47. @AllArgsConstructor
  48. public class UserService {
  49. private UserRepo userRepo;
  50. private WxMaService wxMaService;
  51. private WxMpService wxMpService;
  52. private SmsService smsService;
  53. private StorageService storageService;
  54. private JwtTokenUtil jwtTokenUtil;
  55. private CaptchaService captchaService;
  56. private FollowService followService;
  57. private FollowRepo followRepo;
  58. private IdentityAuthRepo identityAuthRepo;
  59. private SysConfigService sysConfigService;
  60. private CollectionService collectionService;
  61. private AdapayService adapayService;
  62. private UserBankCardRepo userBankCardRepo;
  63. private InviteRepo inviteRepo;
  64. private NFTService nftService;
  65. @CacheEvict(value = "user", key = "#user.username")
  66. public User update(User user) {
  67. User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
  68. ObjUtils.merge(orig, user);
  69. orig = userRepo.save(orig);
  70. userRepo.updateAssetMinter(orig.getId());
  71. userRepo.updateAssetOwner(orig.getId());
  72. userRepo.updateCollectionMinter(orig.getId());
  73. userRepo.updateCollectionOwner(orig.getId());
  74. userRepo.updateOrderMinter(orig.getId());
  75. userRepo.updateHistoryFromUser(orig.getId());
  76. userRepo.updateHistoryToUser(orig.getId());
  77. collectionService.clearCache();
  78. return orig;
  79. }
  80. @CacheEvict(value = "user", allEntries = true)
  81. public void clearCache() {
  82. }
  83. public Page<User> all(PageQuery pageQuery) {
  84. Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);
  85. specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
  86. List<Predicate> and = new ArrayList<>();
  87. and.add(criteriaBuilder.equal(root.get("del"), false));
  88. if (!pageQuery.getQuery().containsKey("admin")) {
  89. and.add(criteriaBuilder.equal(root.get("admin"), false));
  90. }
  91. if (pageQuery.getQuery().containsKey("hasRole")) {
  92. String roleName = (String) pageQuery.getQuery().get("hasRole");
  93. and.add(criteriaBuilder.isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
  94. }
  95. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  96. });
  97. return userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
  98. }
  99. public User create(UserRegister userRegister) {
  100. if (StringUtils.isNoneEmpty(userRegister.getPhone()) && userRepo.findByPhoneAndDelFalse(userRegister.getPhone())
  101. .orElse(null) != null) {
  102. throw new BusinessException("该手机号已注册");
  103. }
  104. User user = new User();
  105. BeanUtils.copyProperties(userRegister, user);
  106. user.setShareRatio(sysConfigService.getBigDecimal("share_ratio"));
  107. user.setAuthStatus(AuthStatus.NOT_AUTH);
  108. if (StringUtils.isNotBlank(userRegister.getPassword())) {
  109. user.setPassword(new BCryptPasswordEncoder().encode(userRegister.getPassword()));
  110. }
  111. user = userRepo.save(user);
  112. User finalUser = user;
  113. new Thread(() -> {
  114. NFTAccount account = nftService.createAccount(finalUser.getUsername() + "_");
  115. finalUser.setNftAccount(account.getAccountId());
  116. finalUser.setKmsId(account.getAccountKmsId());
  117. finalUser.setPublicKey(account.getPublicKey());
  118. userRepo.save(finalUser);
  119. }).start();
  120. return user;
  121. }
  122. public User phoneRegister(String phone, String code, String password, String inviteCode) {
  123. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  124. Invite invite = null;
  125. if (StringUtils.isNotBlank(inviteCode)) {
  126. invite = inviteRepo.findFirstByCode(inviteCode).orElse(null);
  127. }
  128. smsService.verify(phone, code);
  129. User user = create(UserRegister.builder()
  130. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  131. .username(name)
  132. .nickname(name)
  133. .password(password)
  134. .avatar(Constants.DEFAULT_AVATAR)
  135. .phone(phone)
  136. .invitorPhone(Optional.ofNullable(invite).map(Invite::getPhone).orElse(null))
  137. .invitorName(Optional.ofNullable(invite).map(Invite::getName).orElse(null))
  138. .build());
  139. if (invite != null) {
  140. inviteRepo.increaseNum(invite.getId());
  141. }
  142. return user;
  143. }
  144. public void del(Long id) {
  145. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  146. user.setDel(true);
  147. if (StringUtils.isNoneEmpty(user.getOpenId())) {
  148. user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
  149. }
  150. if (StringUtils.isNoneEmpty(user.getPhone())) {
  151. user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
  152. }
  153. userRepo.save(user);
  154. }
  155. public User loginByPhone(String phone, String code) {
  156. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("该手机未注册"));
  157. smsService.verify(phone, code);
  158. if (user == null) {
  159. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  160. user = create(UserRegister.builder()
  161. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  162. .username(name)
  163. .nickname(name)
  164. .avatar(Constants.DEFAULT_AVATAR)
  165. .phone(phone)
  166. .build());
  167. }
  168. return user;
  169. }
  170. public User loginByPhonePwd(String phone, String password) {
  171. if (StringUtils.isEmpty(phone)) {
  172. throw new BusinessException("手机号错误");
  173. }
  174. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  175. if (StringUtils.isEmpty(user.getPassword())) {
  176. throw new BusinessException("账号或密码错误");
  177. }
  178. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  179. !new BCryptPasswordEncoder().matches(password, user.getPassword())) {
  180. throw new BusinessException("账号或密码错误");
  181. }
  182. return user;
  183. }
  184. public User loginMp(String code) throws WxErrorException {
  185. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  186. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  187. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  188. if (user == null) {
  189. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  190. user = User.builder()
  191. .username(name)
  192. .nickname(name)
  193. .avatar(wxMpUser.getHeadImgUrl())
  194. .sex(wxMpUser.getSexDesc())
  195. .country(wxMpUser.getCountry())
  196. .province(wxMpUser.getProvince())
  197. .city(wxMpUser.getCity())
  198. .openId(wxMpUser.getOpenId())
  199. .language(wxMpUser.getLanguage())
  200. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  201. .authStatus(AuthStatus.NOT_AUTH)
  202. .build();
  203. userRepo.save(user);
  204. }
  205. return user;
  206. }
  207. public String code2openId(String code) throws WxErrorException {
  208. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  209. return wxMpService.oauth2getUserInfo(accessToken, null).getOpenId();
  210. }
  211. public User loginMa(String code) {
  212. try {
  213. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  214. String openId = result.getOpenid();
  215. String sessionKey = result.getSessionKey();
  216. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  217. ;
  218. if (userInfo != null) {
  219. return userInfo;
  220. }
  221. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  222. userInfo = User.builder()
  223. .username(name)
  224. .nickname(name)
  225. .openId(openId)
  226. .avatar(Constants.DEFAULT_AVATAR)
  227. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  228. .authStatus(AuthStatus.NOT_AUTH)
  229. .build();
  230. userInfo = userRepo.save(userInfo);
  231. return userInfo;
  232. } catch (WxErrorException e) {
  233. e.printStackTrace();
  234. }
  235. throw new BusinessException("登录失败");
  236. }
  237. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  238. String encryptedData, String iv) {
  239. // 用户信息校验
  240. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  241. throw new BusinessException("获取用户信息失败");
  242. }
  243. // 解密用户信息
  244. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  245. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  246. String avatarUrl = Constants.DEFAULT_AVATAR;
  247. try {
  248. String path = "image/avatar/" +
  249. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  250. RandomStringUtils.randomAlphabetic(8) +
  251. ".jpg";
  252. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  253. } catch (Exception e) {
  254. log.error("获取头像失败", e);
  255. }
  256. if (user == null) {
  257. user = User.builder()
  258. .username(UUID.randomUUID().toString())
  259. .nickname(wxUserInfo.getNickName())
  260. .openId(wxUserInfo.getOpenId())
  261. .avatar(avatarUrl)
  262. .sex(wxUserInfo.getGender())
  263. .country(wxUserInfo.getCountry())
  264. .province(wxUserInfo.getProvince())
  265. .city(wxUserInfo.getCity())
  266. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  267. .build();
  268. user = userRepo.save(user);
  269. } else {
  270. user.setAvatar(avatarUrl);
  271. user.setNickname(wxUserInfo.getNickName());
  272. user.setSex(wxUserInfo.getGender());
  273. user.setCountry(wxUserInfo.getCountry());
  274. user.setProvince(wxUserInfo.getProvince());
  275. user.setCity(wxUserInfo.getCity());
  276. user = userRepo.save(user);
  277. }
  278. return user;
  279. }
  280. public String setPassword(Long userId, String password) {
  281. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  282. user.setPassword(new BCryptPasswordEncoder().encode(password));
  283. user = userRepo.save(user);
  284. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  285. }
  286. public String setPassword(Long userId, String code, String password) {
  287. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  288. smsService.verify(user.getPhone(), code);
  289. return setPassword(userId, password);
  290. }
  291. public String forgotPassword(String phone, String password, String code) {
  292. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("手机号未注册"));
  293. smsService.verify(user.getPhone(), code);
  294. return setPassword(user.getId(), password);
  295. }
  296. public void bindPhone(Long userId, String phone) {
  297. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  298. if (StringUtils.isNoneEmpty(user.getPhone())) {
  299. throw new BusinessException("该账号已绑定手机");
  300. }
  301. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  302. if (!user1.getId().equals(userId)) {
  303. throw new BusinessException("该手机号已绑定其他账号");
  304. }
  305. });
  306. user.setPhone(phone);
  307. userRepo.save(user);
  308. }
  309. public UserDTO toDTO(User user) {
  310. return toDTO(user, true);
  311. }
  312. public UserDTO toDTO(User user, boolean join) {
  313. UserDTO userDTO = new UserDTO();
  314. BeanUtils.copyProperties(user, userDTO);
  315. if (user.getAuthorities() != null) {
  316. userDTO.setAuthorities(new HashSet<>(user.getAuthorities()));
  317. }
  318. if (join) {
  319. if (SecurityUtils.getAuthenticatedUser() != null) {
  320. userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
  321. }
  322. }
  323. return userDTO;
  324. }
  325. public List<UserDTO> toDTO(List<User> users) {
  326. List<Follow> follows = new ArrayList<>();
  327. if (SecurityUtils.getAuthenticatedUser() != null) {
  328. follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  329. }
  330. return users.stream().parallel().map(user -> {
  331. UserDTO dto = toDTO(user, false);
  332. if (!follows.isEmpty()) {
  333. dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
  334. }
  335. return dto;
  336. }).collect(Collectors.toList());
  337. }
  338. public Page<UserDTO> toDTO(Page<User> users) {
  339. List<UserDTO> userDTOS = toDTO(users.getContent());
  340. return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
  341. }
  342. @CacheEvict(value = "user", allEntries = true)
  343. public void setTradeCode(Long userId, String token, String tradeCode) {
  344. String phone = smsService.verifyToken(token);
  345. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  346. if (!StringUtils.equals(phone, user.getPhone())) {
  347. throw new BusinessException("验证码无效");
  348. }
  349. user.setTradeCode(new BCryptPasswordEncoder().encode(tradeCode));
  350. userRepo.save(user);
  351. }
  352. public void verifyTradeCode(Long userId, String tradeCode) {
  353. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  354. if (!new BCryptPasswordEncoder().matches(tradeCode, user.getTradeCode())) {
  355. throw new BusinessException("校验失败");
  356. }
  357. }
  358. public Map<String, Object> searchByPhone(String phone) {
  359. if (AuthStatus.SUCCESS != SecurityUtils.getAuthenticatedUser().getAuthStatus()) {
  360. throw new BusinessException("实名认证后才能赠送");
  361. }
  362. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("用户不存在或未认证"));
  363. if (AuthStatus.SUCCESS != user.getAuthStatus()) {
  364. throw new BusinessException("用户不存在或未认证");
  365. }
  366. String realName = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(
  367. user.getId(), AuthStatus.SUCCESS)
  368. .map(IdentityAuth::getRealName).orElse("").replaceAll(".*(?=.)", "**");
  369. Map<String, Object> map = new HashMap<>();
  370. map.put("id", user.getId());
  371. map.put("avatar", user.getAvatar());
  372. map.put("phone", user.getPhone().replaceAll("(?<=.{3}).*(?=.{4})", "**"));
  373. map.put("realName", realName);
  374. return map;
  375. }
  376. public Map<String, Object> searchByPhoneAdmin(String phoneStr) {
  377. List<String> phone = Arrays.stream(phoneStr.replaceAll("\n", " ")
  378. .replaceAll("\r\n", " ")
  379. .split(" "))
  380. .map(String::trim)
  381. .filter(s -> !StringUtils.isEmpty(s))
  382. .collect(Collectors.toList());
  383. List<User> users = userRepo.findByPhoneInAndDelFalse(phone);
  384. Map<String, Object> map = new HashMap<>();
  385. map.put("users", users);
  386. List<String> notFound = phone.stream().filter(p -> users.stream().noneMatch(u -> p.equals(u.getPhone())))
  387. .collect(Collectors.toList());
  388. map.put("notFound", notFound);
  389. return map;
  390. }
  391. public void addBankCard(Long userId, String bankNo, String phone, String code) throws BaseAdaPayException {
  392. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  393. IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
  394. .orElseThrow(new BusinessException("用户未认证"));
  395. if (identityAuth.isOrg()) {
  396. //throw new BusinessException("企业认证用户请绑定对公账户");
  397. }
  398. if (!StringUtils.isBlank(user.getSettleAccountId())) {
  399. throw new BusinessException("此账号已绑定");
  400. }
  401. BankValidate bankValidate = BankUtils.validate(bankNo);
  402. if (!bankValidate.isValidated()) {
  403. throw new BusinessException("暂不支持此卡");
  404. }
  405. if (StringUtils.isEmpty(user.getMemberId())) {
  406. user.setMemberId(adapayService.createMember(userId, user.getPhone(), identityAuth.getRealName(),
  407. identityAuth.getIdNo()));
  408. userRepo.save(user);
  409. }
  410. smsService.verify(phone, code);
  411. String accountId = adapayService.createSettleAccount(user.getMemberId(), identityAuth.getRealName(),
  412. identityAuth.getIdNo(), phone, bankNo);
  413. user.setSettleAccountId(accountId);
  414. userRepo.save(user);
  415. userBankCardRepo.save(UserBankCard.builder()
  416. .bank(bankValidate.getBank())
  417. .bankName(bankValidate.getBankName())
  418. .bankNo(bankNo)
  419. .cardType(bankValidate.getCardType())
  420. .cardTypeDesc(bankValidate.getCardTypeDesc())
  421. .userId(userId)
  422. .build());
  423. }
  424. public void removeBankCard(Long userId) throws BaseAdaPayException {
  425. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  426. if (StringUtils.isNotBlank(user.getSettleAccountId()) && StringUtils.isNotBlank(user.getMemberId())) {
  427. adapayService.delSettleAccount(user.getMemberId(), user.getSettleAccountId());
  428. user.setSettleAccountId(null);
  429. userRepo.save(user);
  430. userBankCardRepo.deleteByUserId(userId);
  431. } else {
  432. throw new BusinessException("未绑定");
  433. }
  434. }
  435. public Map<String, Object> batchRegister(String phones, String defaultPassword) {
  436. List<String> exist = new ArrayList<>();
  437. List<String> err = new ArrayList<>();
  438. List<String> success = new ArrayList<>();
  439. Arrays.stream(phones.replaceAll(",", " ")
  440. .replaceAll(",", " ")
  441. .replaceAll("\n", " ")
  442. .replaceAll("\r\n", " ")
  443. .split(" ")).forEach(phone -> {
  444. if (userRepo.findByPhoneAndDelFalse(phone).isPresent()) {
  445. exist.add(phone);
  446. } else {
  447. if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
  448. err.add(phone);
  449. } else {
  450. try {
  451. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  452. User user = create(UserRegister.builder()
  453. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  454. .username(name)
  455. .nickname(name)
  456. .password(defaultPassword)
  457. .avatar(Constants.DEFAULT_AVATAR)
  458. .phone(phone)
  459. .build());
  460. success.add(phone);
  461. } catch (Exception e) {
  462. log.error("注册失败", e);
  463. err.add(phone);
  464. }
  465. }
  466. }
  467. });
  468. Map<String, Object> map = new HashMap<>();
  469. map.put("exist", exist);
  470. map.put("error", err);
  471. map.put("success", success);
  472. return map;
  473. }
  474. }