UserService.java 17 KB

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