UserService.java 18 KB

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