UserService.java 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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.User;
  7. import com.izouma.nineth.dto.PageQuery;
  8. import com.izouma.nineth.dto.UserRegister;
  9. import com.izouma.nineth.enums.AuthorityName;
  10. import com.izouma.nineth.exception.BusinessException;
  11. import com.izouma.nineth.repo.UserRepo;
  12. import com.izouma.nineth.security.Authority;
  13. import com.izouma.nineth.security.JwtTokenUtil;
  14. import com.izouma.nineth.security.JwtUserFactory;
  15. import com.izouma.nineth.service.sms.SmsService;
  16. import com.izouma.nineth.service.storage.StorageService;
  17. import com.izouma.nineth.utils.JpaUtils;
  18. import lombok.AllArgsConstructor;
  19. import lombok.extern.slf4j.Slf4j;
  20. import me.chanjar.weixin.common.error.WxErrorException;
  21. import me.chanjar.weixin.mp.api.WxMpService;
  22. import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
  23. import me.chanjar.weixin.mp.bean.result.WxMpUser;
  24. import org.apache.commons.lang3.RandomStringUtils;
  25. import org.apache.commons.lang3.StringUtils;
  26. import org.springframework.beans.BeanUtils;
  27. import org.springframework.data.domain.Page;
  28. import org.springframework.data.jpa.domain.Specification;
  29. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  30. import org.springframework.stereotype.Service;
  31. import javax.persistence.criteria.CriteriaBuilder;
  32. import javax.persistence.criteria.CriteriaQuery;
  33. import javax.persistence.criteria.Predicate;
  34. import javax.persistence.criteria.Root;
  35. import java.text.SimpleDateFormat;
  36. import java.util.*;
  37. @Service
  38. @Slf4j
  39. @AllArgsConstructor
  40. public class UserService {
  41. private UserRepo userRepo;
  42. private WxMaService wxMaService;
  43. private WxMpService wxMpService;
  44. private SmsService smsService;
  45. private StorageService storageService;
  46. private JwtTokenUtil jwtTokenUtil;
  47. private CaptchaService captchaService;
  48. public Page<User> all(PageQuery pageQuery) {
  49. Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);
  50. if (pageQuery.getQuery().containsKey("hasRole")) {
  51. String roleName = (String) pageQuery.getQuery().get("hasRole");
  52. specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) ->
  53. criteriaBuilder.isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
  54. }
  55. return userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
  56. }
  57. public User create(UserRegister userRegister) {
  58. if (StringUtils.isNoneEmpty(userRegister.getPhone()) && userRepo.findByPhoneAndDelFalse(userRegister.getPhone()) != null) {
  59. throw new BusinessException("该手机号已注册");
  60. }
  61. User user = new User();
  62. BeanUtils.copyProperties(userRegister, user);
  63. if (StringUtils.isNotBlank(userRegister.getPassword())) {
  64. user.setPassword(new BCryptPasswordEncoder().encode(userRegister.getPassword()));
  65. }
  66. return userRepo.save(user);
  67. }
  68. public void del(Long id) {
  69. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  70. user.setDel(true);
  71. if (StringUtils.isNoneEmpty(user.getOpenId())) {
  72. user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
  73. }
  74. if (StringUtils.isNoneEmpty(user.getPhone())) {
  75. user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
  76. }
  77. userRepo.save(user);
  78. }
  79. public User loginByPhone(String phone, String code) {
  80. smsService.verify(phone, code);
  81. User user = userRepo.findByPhoneAndDelFalse(phone).orElse(null);
  82. ;
  83. if (user == null) {
  84. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  85. user = create(UserRegister.builder()
  86. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  87. .username(name)
  88. .nickname(name)
  89. .avatar(Constants.DEFAULT_AVATAR)
  90. .phone(phone)
  91. .build());
  92. }
  93. return user;
  94. }
  95. public User loginByPhonePwd(String phone, String password) {
  96. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  97. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  98. new BCryptPasswordEncoder().matches(password, user.getPassword())) {
  99. throw new BusinessException("账号或密码错误");
  100. }
  101. return user;
  102. }
  103. public User loginMp(String code) throws WxErrorException {
  104. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  105. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  106. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  107. if (user == null) {
  108. user = User.builder()
  109. .username(UUID.randomUUID().toString())
  110. .nickname(wxMpUser.getNickname())
  111. .avatar(wxMpUser.getHeadImgUrl())
  112. .sex(wxMpUser.getSexDesc())
  113. .country(wxMpUser.getCountry())
  114. .province(wxMpUser.getProvince())
  115. .city(wxMpUser.getCity())
  116. .openId(wxMpUser.getOpenId())
  117. .language(wxMpUser.getLanguage())
  118. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  119. .build();
  120. userRepo.save(user);
  121. }
  122. return user;
  123. }
  124. public User loginMa(String code) {
  125. try {
  126. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  127. String openId = result.getOpenid();
  128. String sessionKey = result.getSessionKey();
  129. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  130. ;
  131. if (userInfo != null) {
  132. return userInfo;
  133. }
  134. userInfo = User.builder()
  135. .username(UUID.randomUUID().toString())
  136. .nickname("用户" + RandomStringUtils.randomAlphabetic(6))
  137. .openId(openId)
  138. .avatar(Constants.DEFAULT_AVATAR)
  139. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  140. .build();
  141. userInfo = userRepo.save(userInfo);
  142. return userInfo;
  143. } catch (WxErrorException e) {
  144. e.printStackTrace();
  145. }
  146. throw new BusinessException("登录失败");
  147. }
  148. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  149. String encryptedData, String iv) {
  150. // 用户信息校验
  151. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  152. throw new BusinessException("获取用户信息失败");
  153. }
  154. // 解密用户信息
  155. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  156. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  157. ;
  158. String avatarUrl = Constants.DEFAULT_AVATAR;
  159. try {
  160. String path = "image/avatar/" +
  161. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  162. RandomStringUtils.randomAlphabetic(8) +
  163. ".jpg";
  164. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  165. } catch (Exception e) {
  166. log.error("获取头像失败", e);
  167. }
  168. if (user == null) {
  169. user = User.builder()
  170. .username(UUID.randomUUID().toString())
  171. .nickname(wxUserInfo.getNickName())
  172. .openId(wxUserInfo.getOpenId())
  173. .avatar(avatarUrl)
  174. .sex(wxUserInfo.getGender())
  175. .country(wxUserInfo.getCountry())
  176. .province(wxUserInfo.getProvince())
  177. .city(wxUserInfo.getCity())
  178. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  179. .build();
  180. user = userRepo.save(user);
  181. } else {
  182. user.setAvatar(avatarUrl);
  183. user.setNickname(wxUserInfo.getNickName());
  184. user.setSex(wxUserInfo.getGender());
  185. user.setCountry(wxUserInfo.getCountry());
  186. user.setProvince(wxUserInfo.getProvince());
  187. user.setCity(wxUserInfo.getCity());
  188. user = userRepo.save(user);
  189. }
  190. return user;
  191. }
  192. public String setPassword(Long userId, String password) {
  193. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  194. user.setPassword(new BCryptPasswordEncoder().encode(password));
  195. user = userRepo.save(user);
  196. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  197. }
  198. public String setPassword(Long userId, String key, String code, String password) {
  199. if (!captchaService.verify(key, code)) {
  200. throw new BusinessException("验证码错误");
  201. }
  202. return setPassword(userId, password);
  203. }
  204. public void bindPhone(Long userId, String phone) {
  205. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  206. if (StringUtils.isNoneEmpty(user.getPhone())) {
  207. throw new BusinessException("该账号已绑定手机");
  208. }
  209. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  210. if (!user1.getId().equals(userId)) {
  211. throw new BusinessException("该手机号已绑定其他账号");
  212. }
  213. });
  214. user.setPhone(phone);
  215. userRepo.save(user);
  216. }
  217. }