UserService.java 14 KB

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