UserService.java 19 KB

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