UserService.java 10 KB

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