UserService.java 14 KB

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