UserService.java 15 KB

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