UserService.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 User phoneRegister(String phone, String code, String password) {
  70. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  71. User user = create(UserRegister.builder()
  72. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  73. .username(name)
  74. .nickname(name)
  75. .avatar(Constants.DEFAULT_AVATAR)
  76. .phone(phone)
  77. .build());
  78. return user;
  79. }
  80. public void del(Long id) {
  81. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  82. user.setDel(true);
  83. if (StringUtils.isNoneEmpty(user.getOpenId())) {
  84. user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
  85. }
  86. if (StringUtils.isNoneEmpty(user.getPhone())) {
  87. user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
  88. }
  89. userRepo.save(user);
  90. }
  91. public User loginByPhone(String phone, String code) {
  92. smsService.verify(phone, code);
  93. User user = userRepo.findByPhoneAndDelFalse(phone).orElse(null);
  94. if (user == null) {
  95. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  96. user = create(UserRegister.builder()
  97. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  98. .username(name)
  99. .nickname(name)
  100. .avatar(Constants.DEFAULT_AVATAR)
  101. .phone(phone)
  102. .build());
  103. }
  104. return user;
  105. }
  106. public User loginByPhonePwd(String phone, String password) {
  107. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  108. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  109. new BCryptPasswordEncoder().matches(password, user.getPassword())) {
  110. throw new BusinessException("账号或密码错误");
  111. }
  112. return user;
  113. }
  114. public User loginMp(String code) throws WxErrorException {
  115. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  116. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  117. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  118. if (user == null) {
  119. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  120. user = User.builder()
  121. .username(name)
  122. .nickname(name)
  123. .avatar(wxMpUser.getHeadImgUrl())
  124. .sex(wxMpUser.getSexDesc())
  125. .country(wxMpUser.getCountry())
  126. .province(wxMpUser.getProvince())
  127. .city(wxMpUser.getCity())
  128. .openId(wxMpUser.getOpenId())
  129. .language(wxMpUser.getLanguage())
  130. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  131. .authStatus(AuthStatus.NOT_AUTH)
  132. .build();
  133. userRepo.save(user);
  134. }
  135. return user;
  136. }
  137. public User loginMa(String code) {
  138. try {
  139. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  140. String openId = result.getOpenid();
  141. String sessionKey = result.getSessionKey();
  142. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  143. ;
  144. if (userInfo != null) {
  145. return userInfo;
  146. }
  147. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  148. userInfo = User.builder()
  149. .username(name)
  150. .nickname(name)
  151. .openId(openId)
  152. .avatar(Constants.DEFAULT_AVATAR)
  153. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  154. .authStatus(AuthStatus.NOT_AUTH)
  155. .build();
  156. userInfo = userRepo.save(userInfo);
  157. return userInfo;
  158. } catch (WxErrorException e) {
  159. e.printStackTrace();
  160. }
  161. throw new BusinessException("登录失败");
  162. }
  163. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  164. String encryptedData, String iv) {
  165. // 用户信息校验
  166. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  167. throw new BusinessException("获取用户信息失败");
  168. }
  169. // 解密用户信息
  170. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  171. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  172. String avatarUrl = Constants.DEFAULT_AVATAR;
  173. try {
  174. String path = "image/avatar/" +
  175. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  176. RandomStringUtils.randomAlphabetic(8) +
  177. ".jpg";
  178. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  179. } catch (Exception e) {
  180. log.error("获取头像失败", e);
  181. }
  182. if (user == null) {
  183. user = User.builder()
  184. .username(UUID.randomUUID().toString())
  185. .nickname(wxUserInfo.getNickName())
  186. .openId(wxUserInfo.getOpenId())
  187. .avatar(avatarUrl)
  188. .sex(wxUserInfo.getGender())
  189. .country(wxUserInfo.getCountry())
  190. .province(wxUserInfo.getProvince())
  191. .city(wxUserInfo.getCity())
  192. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  193. .build();
  194. user = userRepo.save(user);
  195. } else {
  196. user.setAvatar(avatarUrl);
  197. user.setNickname(wxUserInfo.getNickName());
  198. user.setSex(wxUserInfo.getGender());
  199. user.setCountry(wxUserInfo.getCountry());
  200. user.setProvince(wxUserInfo.getProvince());
  201. user.setCity(wxUserInfo.getCity());
  202. user = userRepo.save(user);
  203. }
  204. return user;
  205. }
  206. public String setPassword(Long userId, String password) {
  207. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  208. user.setPassword(new BCryptPasswordEncoder().encode(password));
  209. user = userRepo.save(user);
  210. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  211. }
  212. public String setPassword(Long userId, String key, String code, String password) {
  213. if (!captchaService.verify(key, code)) {
  214. throw new BusinessException("验证码错误");
  215. }
  216. return setPassword(userId, password);
  217. }
  218. public void bindPhone(Long userId, String phone) {
  219. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  220. if (StringUtils.isNoneEmpty(user.getPhone())) {
  221. throw new BusinessException("该账号已绑定手机");
  222. }
  223. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  224. if (!user1.getId().equals(userId)) {
  225. throw new BusinessException("该手机号已绑定其他账号");
  226. }
  227. });
  228. user.setPhone(phone);
  229. userRepo.save(user);
  230. }
  231. }