UserService.java 22 KB

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