UserService.java 17 KB

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