UserService.java 16 KB

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