UserService.java 13 KB

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