UserService.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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.isNoneEmpty(user.getPassword()) &&
  115. new BCryptPasswordEncoder().matches(password, user.getPassword())) {
  116. throw new BusinessException("账号或密码错误");
  117. }
  118. return user;
  119. }
  120. public User loginMp(String code) throws WxErrorException {
  121. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  122. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  123. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  124. if (user == null) {
  125. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  126. user = User.builder()
  127. .username(name)
  128. .nickname(name)
  129. .avatar(wxMpUser.getHeadImgUrl())
  130. .sex(wxMpUser.getSexDesc())
  131. .country(wxMpUser.getCountry())
  132. .province(wxMpUser.getProvince())
  133. .city(wxMpUser.getCity())
  134. .openId(wxMpUser.getOpenId())
  135. .language(wxMpUser.getLanguage())
  136. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  137. .authStatus(AuthStatus.NOT_AUTH)
  138. .build();
  139. userRepo.save(user);
  140. }
  141. return user;
  142. }
  143. public User loginMa(String code) {
  144. try {
  145. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  146. String openId = result.getOpenid();
  147. String sessionKey = result.getSessionKey();
  148. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  149. ;
  150. if (userInfo != null) {
  151. return userInfo;
  152. }
  153. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  154. userInfo = User.builder()
  155. .username(name)
  156. .nickname(name)
  157. .openId(openId)
  158. .avatar(Constants.DEFAULT_AVATAR)
  159. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  160. .authStatus(AuthStatus.NOT_AUTH)
  161. .build();
  162. userInfo = userRepo.save(userInfo);
  163. return userInfo;
  164. } catch (WxErrorException e) {
  165. e.printStackTrace();
  166. }
  167. throw new BusinessException("登录失败");
  168. }
  169. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  170. String encryptedData, String iv) {
  171. // 用户信息校验
  172. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  173. throw new BusinessException("获取用户信息失败");
  174. }
  175. // 解密用户信息
  176. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  177. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  178. String avatarUrl = Constants.DEFAULT_AVATAR;
  179. try {
  180. String path = "image/avatar/" +
  181. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  182. RandomStringUtils.randomAlphabetic(8) +
  183. ".jpg";
  184. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  185. } catch (Exception e) {
  186. log.error("获取头像失败", e);
  187. }
  188. if (user == null) {
  189. user = User.builder()
  190. .username(UUID.randomUUID().toString())
  191. .nickname(wxUserInfo.getNickName())
  192. .openId(wxUserInfo.getOpenId())
  193. .avatar(avatarUrl)
  194. .sex(wxUserInfo.getGender())
  195. .country(wxUserInfo.getCountry())
  196. .province(wxUserInfo.getProvince())
  197. .city(wxUserInfo.getCity())
  198. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  199. .build();
  200. user = userRepo.save(user);
  201. } else {
  202. user.setAvatar(avatarUrl);
  203. user.setNickname(wxUserInfo.getNickName());
  204. user.setSex(wxUserInfo.getGender());
  205. user.setCountry(wxUserInfo.getCountry());
  206. user.setProvince(wxUserInfo.getProvince());
  207. user.setCity(wxUserInfo.getCity());
  208. user = userRepo.save(user);
  209. }
  210. return user;
  211. }
  212. public String setPassword(Long userId, String password) {
  213. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  214. user.setPassword(new BCryptPasswordEncoder().encode(password));
  215. user = userRepo.save(user);
  216. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  217. }
  218. public String setPassword(Long userId, String key, String code, String password) {
  219. if (!captchaService.verify(key, code)) {
  220. throw new BusinessException("验证码错误");
  221. }
  222. return setPassword(userId, password);
  223. }
  224. public void bindPhone(Long userId, String phone) {
  225. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  226. if (StringUtils.isNoneEmpty(user.getPhone())) {
  227. throw new BusinessException("该账号已绑定手机");
  228. }
  229. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  230. if (!user1.getId().equals(userId)) {
  231. throw new BusinessException("该手机号已绑定其他账号");
  232. }
  233. });
  234. user.setPhone(phone);
  235. userRepo.save(user);
  236. }
  237. public UserDTO toDTO(User user) {
  238. return toDTO(user, true);
  239. }
  240. public UserDTO toDTO(User user, boolean join) {
  241. UserDTO userDTO = new UserDTO();
  242. BeanUtils.copyProperties(user, userDTO);
  243. if (join) {
  244. if (SecurityUtils.getAuthenticatedUser() != null) {
  245. userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
  246. }
  247. }
  248. return userDTO;
  249. }
  250. public List<UserDTO> toDTO(List<User> users) {
  251. List<Follow> follows = new ArrayList<>();
  252. if (SecurityUtils.getAuthenticatedUser() != null) {
  253. follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  254. }
  255. return users.stream().parallel().map(user -> {
  256. UserDTO dto = toDTO(user, false);
  257. if (!follows.isEmpty()) {
  258. dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
  259. }
  260. return dto;
  261. }).collect(Collectors.toList());
  262. }
  263. public Page<UserDTO> toDTO(Page<User> users) {
  264. List<UserDTO> userDTOS = toDTO(users.getContent());
  265. return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
  266. }
  267. }