UserService.java 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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.alibaba.fastjson.JSONObject;
  6. import com.fasterxml.jackson.core.sym.NameN;
  7. import com.huifu.adapay.core.exception.BaseAdaPayException;
  8. import com.izouma.nineth.TokenHistory;
  9. import com.izouma.nineth.config.Constants;
  10. import com.izouma.nineth.config.GeneralProperties;
  11. import com.izouma.nineth.config.RedisKeys;
  12. import com.izouma.nineth.domain.Collection;
  13. import com.izouma.nineth.domain.*;
  14. import com.izouma.nineth.dto.*;
  15. import com.izouma.nineth.enums.AuthStatus;
  16. import com.izouma.nineth.enums.AuthorityName;
  17. import com.izouma.nineth.event.AccountCreatedEvent;
  18. import com.izouma.nineth.event.RegisterEvent;
  19. import com.izouma.nineth.exception.BusinessException;
  20. import com.izouma.nineth.repo.*;
  21. import com.izouma.nineth.security.Authority;
  22. import com.izouma.nineth.security.JwtTokenUtil;
  23. import com.izouma.nineth.security.JwtUserFactory;
  24. import com.izouma.nineth.service.sms.SmsService;
  25. import com.izouma.nineth.service.storage.StorageService;
  26. import com.izouma.nineth.utils.BankUtils;
  27. import com.izouma.nineth.utils.JpaUtils;
  28. import com.izouma.nineth.utils.ObjUtils;
  29. import com.izouma.nineth.utils.SecurityUtils;
  30. import lombok.AllArgsConstructor;
  31. import lombok.extern.slf4j.Slf4j;
  32. import me.chanjar.weixin.common.error.WxErrorException;
  33. import me.chanjar.weixin.mp.api.WxMpService;
  34. import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
  35. import me.chanjar.weixin.mp.bean.result.WxMpUser;
  36. import org.apache.commons.lang3.ObjectUtils;
  37. import org.apache.commons.lang3.RandomStringUtils;
  38. import org.apache.commons.lang3.StringUtils;
  39. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  40. import org.springframework.beans.BeanUtils;
  41. import org.springframework.cache.annotation.CacheEvict;
  42. import org.springframework.cache.annotation.Cacheable;
  43. import org.springframework.context.event.EventListener;
  44. import org.springframework.core.env.Environment;
  45. import org.springframework.data.domain.Page;
  46. import org.springframework.data.domain.PageImpl;
  47. import org.springframework.data.domain.PageRequest;
  48. import org.springframework.data.domain.Sort;
  49. import org.springframework.data.jpa.domain.Specification;
  50. import org.springframework.data.redis.core.RedisTemplate;
  51. import org.springframework.scheduling.annotation.Async;
  52. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  53. import org.springframework.security.crypto.password.PasswordEncoder;
  54. import org.springframework.stereotype.Service;
  55. import javax.persistence.criteria.CriteriaBuilder;
  56. import javax.persistence.criteria.CriteriaQuery;
  57. import javax.persistence.criteria.Predicate;
  58. import javax.persistence.criteria.Root;
  59. import java.math.BigDecimal;
  60. import java.math.BigInteger;
  61. import java.text.SimpleDateFormat;
  62. import java.time.Duration;
  63. import java.time.LocalDate;
  64. import java.time.format.DateTimeFormatter;
  65. import java.time.temporal.ChronoUnit;
  66. import java.util.*;
  67. import java.util.concurrent.atomic.AtomicInteger;
  68. import java.util.regex.Pattern;
  69. import java.util.stream.Collectors;
  70. @Service
  71. @Slf4j
  72. @AllArgsConstructor
  73. public class UserService {
  74. private UserRepo userRepo;
  75. private WxMaService wxMaService;
  76. private WxMpService wxMpService;
  77. private SmsService smsService;
  78. private StorageService storageService;
  79. private JwtTokenUtil jwtTokenUtil;
  80. private FollowService followService;
  81. private FollowRepo followRepo;
  82. private IdentityAuthRepo identityAuthRepo;
  83. private SysConfigService sysConfigService;
  84. private UserBankCardRepo userBankCardRepo;
  85. private InviteRepo inviteRepo;
  86. private CacheService cacheService;
  87. private TokenHistoryRepo tokenHistoryRepo;
  88. private CollectionRepo collectionRepo;
  89. private AdapayMerchantService adapayMerchantService;
  90. private RocketMQTemplate rocketMQTemplate;
  91. private GeneralProperties generalProperties;
  92. private RedisTemplate<String, Object> redisTemplate;
  93. private PasswordEncoder passwordEncoder;
  94. private WeakPassRepo weakPassRepo;
  95. private UserBalanceRepo userBalanceRepo;
  96. private ContentAuditService contentAuditService;
  97. private OrderRepo orderRepo;
  98. public User update(User user) {
  99. if (!SecurityUtils.hasRole(AuthorityName.ROLE_ADMIN)) {
  100. if (!SecurityUtils.getAuthenticatedUser().getId().equals(user.getId())) {
  101. throw new BusinessException("无权限");
  102. }
  103. }
  104. User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
  105. ObjUtils.merge(orig, user);
  106. orig = save(orig);
  107. userRepo.updateAssetMinter(orig.getId());
  108. userRepo.updateAssetOwner(orig.getId());
  109. userRepo.updateCollectionMinter(orig.getId());
  110. userRepo.updateCollectionOwner(orig.getId());
  111. userRepo.updateOrderMinter(orig.getId());
  112. userRepo.updateHistoryFromUser(orig.getId());
  113. userRepo.updateHistoryToUser(orig.getId());
  114. userRepo.updateShowroomToUser(orig.getId());
  115. cacheService.clearCollection();
  116. return orig;
  117. }
  118. public User save(User user) {
  119. if (user.getId() != null) {
  120. cacheService.clearUserMy(user.getId());
  121. cacheService.clearUser(user.getId());
  122. }
  123. return userRepo.save(user);
  124. }
  125. public User update(Long userId, String nickname, String avatar, String sex, String bg, String intro,
  126. Boolean useCollectionPic, Boolean riskWarning, Integer level) {
  127. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  128. if (StringUtils.isNotBlank(nickname)) {
  129. if (!nickname.equals(user.getNickname())) {
  130. if (!contentAuditService.auditText(nickname)) {
  131. throw new BusinessException("昵称包含非法内容");
  132. }
  133. }
  134. user.setNickname(nickname);
  135. }
  136. if (StringUtils.isNotBlank(avatar)) {
  137. user.setAvatar(avatar);
  138. }
  139. if (StringUtils.isNotBlank(sex)) {
  140. user.setSex(sex);
  141. }
  142. if (StringUtils.isNotBlank(bg)) {
  143. user.setBg(bg);
  144. }
  145. if (StringUtils.isNotBlank(intro)) {
  146. if (!intro.equals(user.getIntro())) {
  147. if (!contentAuditService.auditText(nickname)) {
  148. throw new BusinessException("简介包含非法内容");
  149. }
  150. }
  151. user.setIntro(intro);
  152. }
  153. if (useCollectionPic != null) {
  154. user.setUseCollectionPic(useCollectionPic);
  155. }
  156. if (riskWarning != null) {
  157. user.setRiskWarning(riskWarning);
  158. }
  159. if (level != null) {
  160. user.setLevel(level);
  161. }
  162. user = save(user);
  163. userRepo.updateAssetMinter(userId);
  164. userRepo.updateAssetOwner(userId);
  165. userRepo.updateCollectionMinter(userId);
  166. userRepo.updateCollectionOwner(userId);
  167. userRepo.updateOrderMinter(userId);
  168. userRepo.updateHistoryFromUser(userId);
  169. userRepo.updateHistoryToUser(userId);
  170. userRepo.updateShowroomToUser(userId);
  171. return user;
  172. }
  173. @Cacheable(value = "userList", key = "#pageQuery.hashCode()")
  174. public PageWrapper<User> all(PageQuery pageQuery) {
  175. Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);
  176. specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
  177. List<Predicate> and = new ArrayList<>();
  178. and.add(criteriaBuilder.equal(root.get("del"), false));
  179. if (!pageQuery.getQuery().containsKey("admin")) {
  180. and.add(criteriaBuilder.equal(root.get("admin"), false));
  181. }
  182. if (pageQuery.getQuery().containsKey("hasRole")) {
  183. String roleName = (String) pageQuery.getQuery().get("hasRole");
  184. if (roleName.equals("ROLE_MINTER")) {
  185. and.add(criteriaBuilder.equal(root.get("minter"), true));
  186. } else {
  187. and.add(criteriaBuilder
  188. .isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
  189. }
  190. }
  191. if (pageQuery.getQuery().containsKey("vip")) {
  192. boolean vip = (boolean) pageQuery.getQuery().get("vip");
  193. if (vip) {
  194. and.add(criteriaBuilder.greaterThan(root.get("vipPurchase"), 0));
  195. } else {
  196. and.add(criteriaBuilder.lessThanOrEqualTo(root.get("vipPurchase"), 0));
  197. }
  198. }
  199. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  200. });
  201. Page<User> page = userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
  202. return PageWrapper.of(page);
  203. }
  204. public User create(UserRegister userRegister) {
  205. User user = new User();
  206. BeanUtils.copyProperties(userRegister, user);
  207. user.setShareRatio(sysConfigService.getBigDecimal("share_ratio"));
  208. user.setAuthStatus(AuthStatus.NOT_AUTH);
  209. if (StringUtils.isNotBlank(userRegister.getPassword())) {
  210. checkPasswordStrength(userRegister.getPassword());
  211. user.setPassword(passwordEncoder.encode(userRegister.getPassword()));
  212. }
  213. return save(user);
  214. }
  215. public User phoneRegister(String phone, String code, String password, String inviteCode, Long invitor, Long collectionId) {
  216. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  217. Invite invite = null;
  218. if (StringUtils.isNotBlank(inviteCode)) {
  219. invite = inviteRepo.findFirstByCode(inviteCode).orElse(null);
  220. }
  221. smsService.verify(phone, code);
  222. Collection collection;
  223. if (collectionId != null) {
  224. collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("无藏品"));
  225. // if (!collection.isOnShelf() || !collection.isSalable()) {
  226. // collectionId = null;
  227. // } else if (collection.isScheduleSale()) {
  228. // if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  229. // collectionId = null;
  230. // }
  231. // }
  232. // 只看是否开去分享
  233. if (ObjectUtils.isEmpty(collection.getOpenQuota()) || !collection.getOpenQuota()) {
  234. collectionId = null;
  235. }
  236. }
  237. User user = create(UserRegister.builder()
  238. .username(name)
  239. .nickname(name)
  240. .password(password)
  241. .avatar(Constants.DEFAULT_AVATAR)
  242. .phone(phone)
  243. .invitorPhone(Optional.ofNullable(invite).map(Invite::getPhone).orElse(null))
  244. .invitorName(Optional.ofNullable(invite).map(Invite::getName).orElse(null))
  245. .inviteCode(Optional.ofNullable(invite).map(Invite::getCode).orElse(null))
  246. .collectionInvitor(invitor)
  247. .collectionId(collectionId)
  248. .build());
  249. if (invite != null) {
  250. inviteRepo.increaseNum(invite.getId());
  251. }
  252. return user;
  253. }
  254. public String mqRegister(String phone, String code, String password, String inviteCode, Long invitor, Long collectionId) {
  255. rocketMQTemplate.convertAndSend(generalProperties.getRegisterTopic(),
  256. new RegisterEvent(phone, code, password, inviteCode, invitor, collectionId));
  257. return phone;
  258. }
  259. public Object getRegisterResult(String phone) {
  260. return redisTemplate.opsForValue().get("register::" + phone);
  261. }
  262. public void del(Long id) {
  263. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  264. user.setDel(true);
  265. if (StringUtils.isNoneEmpty(user.getOpenId())) {
  266. user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
  267. }
  268. if (StringUtils.isNoneEmpty(user.getPhone())) {
  269. user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
  270. }
  271. save(user);
  272. //删除实名认证
  273. identityAuthRepo.softDeleteByUserId(id);
  274. }
  275. public User loginByPhone(String phone, String code) {
  276. User user = userRepo.findByPhoneAndDelFalse(phone).orElse(null);
  277. smsService.verify(phone, code);
  278. if (user == null) {
  279. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  280. user = create(UserRegister.builder()
  281. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  282. .username(name)
  283. .nickname(name)
  284. .avatar(Constants.DEFAULT_AVATAR)
  285. .phone(phone)
  286. .build());
  287. }
  288. return user;
  289. }
  290. public User loginByPhonePwd(String phone, String password) {
  291. if (StringUtils.isEmpty(phone)) {
  292. throw new BusinessException("手机号错误");
  293. }
  294. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  295. if (StringUtils.isEmpty(user.getPassword())) {
  296. throw new BusinessException("账号或密码错误");
  297. }
  298. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  299. !passwordEncoder.matches(password, user.getPassword())) {
  300. throw new BusinessException("账号或密码错误");
  301. }
  302. return user;
  303. }
  304. public User loginByUsernamePwd(String username, String password) {
  305. if (StringUtils.isEmpty(username)) {
  306. throw new BusinessException("用户名错误");
  307. }
  308. User user = userRepo.findByUsernameAndDelFalse(username).orElseThrow(new BusinessException("账号或密码错误"));
  309. if (StringUtils.isEmpty(user.getPassword())
  310. || !passwordEncoder.matches(password, user.getPassword())) {
  311. throw new BusinessException("账号或密码错误");
  312. }
  313. return user;
  314. }
  315. public User loginMp(String code) throws WxErrorException {
  316. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  317. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  318. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  319. if (user == null) {
  320. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  321. user = User.builder()
  322. .username(name)
  323. .nickname(name)
  324. .avatar(wxMpUser.getHeadImgUrl())
  325. .sex(wxMpUser.getSexDesc())
  326. .country(wxMpUser.getCountry())
  327. .province(wxMpUser.getProvince())
  328. .city(wxMpUser.getCity())
  329. .openId(wxMpUser.getOpenId())
  330. .language(wxMpUser.getLanguage())
  331. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  332. .authStatus(AuthStatus.NOT_AUTH)
  333. .build();
  334. save(user);
  335. }
  336. return user;
  337. }
  338. public String code2openId(String code) throws WxErrorException {
  339. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  340. return wxMpService.oauth2getUserInfo(accessToken, null).getOpenId();
  341. }
  342. public User loginMa(String code) {
  343. try {
  344. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  345. String openId = result.getOpenid();
  346. String sessionKey = result.getSessionKey();
  347. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  348. ;
  349. if (userInfo != null) {
  350. return userInfo;
  351. }
  352. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  353. userInfo = User.builder()
  354. .username(name)
  355. .nickname(name)
  356. .openId(openId)
  357. .avatar(Constants.DEFAULT_AVATAR)
  358. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  359. .authStatus(AuthStatus.NOT_AUTH)
  360. .build();
  361. userInfo = save(userInfo);
  362. return userInfo;
  363. } catch (WxErrorException e) {
  364. e.printStackTrace();
  365. }
  366. throw new BusinessException("登录失败");
  367. }
  368. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  369. String encryptedData, String iv) {
  370. // 用户信息校验
  371. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  372. throw new BusinessException("获取用户信息失败");
  373. }
  374. // 解密用户信息
  375. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  376. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  377. String avatarUrl = Constants.DEFAULT_AVATAR;
  378. try {
  379. String path = "image/avatar/" +
  380. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  381. RandomStringUtils.randomAlphabetic(8) +
  382. ".jpg";
  383. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  384. } catch (Exception e) {
  385. log.error("获取头像失败", e);
  386. }
  387. if (user == null) {
  388. user = User.builder()
  389. .username(UUID.randomUUID().toString())
  390. .nickname(wxUserInfo.getNickName())
  391. .openId(wxUserInfo.getOpenId())
  392. .avatar(avatarUrl)
  393. .sex(wxUserInfo.getGender())
  394. .country(wxUserInfo.getCountry())
  395. .province(wxUserInfo.getProvince())
  396. .city(wxUserInfo.getCity())
  397. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  398. .build();
  399. user = save(user);
  400. } else {
  401. user.setAvatar(avatarUrl);
  402. user.setNickname(wxUserInfo.getNickName());
  403. user.setSex(wxUserInfo.getGender());
  404. user.setCountry(wxUserInfo.getCountry());
  405. user.setProvince(wxUserInfo.getProvince());
  406. user.setCity(wxUserInfo.getCity());
  407. user = save(user);
  408. }
  409. return user;
  410. }
  411. public String setPassword(Long userId, String password) {
  412. checkPasswordStrength(password);
  413. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  414. user.setPassword(passwordEncoder.encode(password));
  415. user = save(user);
  416. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  417. }
  418. public String setPassword(Long userId, String code, String password) {
  419. checkPasswordStrength(password);
  420. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  421. smsService.verify(user.getPhone(), code);
  422. return setPassword(userId, password);
  423. }
  424. public String forgotPassword(String phone, String password, String code) {
  425. checkPasswordStrength(password);
  426. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("手机号未注册"));
  427. smsService.verify(user.getPhone(), code);
  428. return setPassword(user.getId(), password);
  429. }
  430. public static void checkPasswordStrength(String password) {
  431. if (StringUtils.isBlank(password)) throw new BusinessException("密码不能为空");
  432. if (!Pattern.matches("^[a-zA-Z0-9!@#$%^&*]+$", password)) throw new BusinessException("密码含非法字符");
  433. int upper = 0;
  434. int lower = 0;
  435. int digit = 0;
  436. int special = 0;
  437. char ch;
  438. for (int i = 0; i < password.length(); i++) {
  439. ch = password.charAt(i);
  440. if (Character.isUpperCase(ch))
  441. upper++;
  442. else if (Character.isLowerCase(ch))
  443. lower++;
  444. else if (Character.isDigit(ch))
  445. digit++;
  446. else {
  447. if (ch == '<' || ch == '>') {
  448. throw new BusinessException("密码包含非法字符");
  449. } else
  450. special++;
  451. }
  452. }
  453. if (upper > 0 && lower > 0 && digit > 0 && password.length() >= 8) {
  454. return;
  455. }
  456. throw new BusinessException("密码长度至少为8位,且必须包含大小写字母和数字");
  457. }
  458. public void bindPhone(Long userId, String phone) {
  459. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  460. if (StringUtils.isNoneEmpty(user.getPhone())) {
  461. throw new BusinessException("该账号已绑定手机");
  462. }
  463. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  464. if (!user1.getId().equals(userId)) {
  465. throw new BusinessException("该手机号已绑定其他账号");
  466. }
  467. });
  468. user.setPhone(phone);
  469. save(user);
  470. }
  471. public UserDTO toDTO(User user) {
  472. return toDTO(user, true);
  473. }
  474. public UserDTO toDTO(User user, boolean join) {
  475. UserDTO userDTO = new UserDTO();
  476. BeanUtils.copyProperties(user, userDTO);
  477. if (user.getAuthorities() != null) {
  478. userDTO.setAuthorities(new HashSet<>(user.getAuthorities()));
  479. }
  480. if (join) {
  481. if (SecurityUtils.getAuthenticatedUser() != null) {
  482. userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
  483. }
  484. }
  485. return userDTO;
  486. }
  487. public List<UserDTO> toDTO(List<User> users) {
  488. List<Follow> follows = new ArrayList<>();
  489. if (SecurityUtils.getAuthenticatedUser() != null) {
  490. follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  491. }
  492. return users.stream().parallel().map(user -> {
  493. UserDTO dto = toDTO(user, false);
  494. if (!follows.isEmpty()) {
  495. dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
  496. }
  497. return dto;
  498. }).collect(Collectors.toList());
  499. }
  500. public Page<UserDTO> toDTO(Page<User> users) {
  501. List<UserDTO> userDTOS = toDTO(users.getContent());
  502. return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
  503. }
  504. @CacheEvict(value = "user", allEntries = true)
  505. public void setTradeCode(Long userId, String token, String tradeCode) {
  506. String phone = smsService.verifyToken(token);
  507. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  508. if (!StringUtils.equals(phone, user.getPhone())) {
  509. throw new BusinessException("验证码无效");
  510. }
  511. user.setTradeCode(passwordEncoder.encode(tradeCode));
  512. save(user);
  513. }
  514. public void verifyTradeCode(Long userId, String tradeCode) {
  515. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  516. if (!passwordEncoder.matches(tradeCode, user.getTradeCode())) {
  517. throw new BusinessException("交易密码错误");
  518. }
  519. }
  520. public Map<String, Object> searchByPhone(String phone) {
  521. if (AuthStatus.SUCCESS != SecurityUtils.getAuthenticatedUser().getAuthStatus()) {
  522. throw new BusinessException("实名认证后才能赠送");
  523. }
  524. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("用户不存在或未认证"));
  525. if (AuthStatus.SUCCESS != user.getAuthStatus()) {
  526. throw new BusinessException("用户不存在或未认证");
  527. }
  528. String realName = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(
  529. user.getId(), AuthStatus.SUCCESS)
  530. .map(IdentityAuth::getRealName).orElse("").replaceAll(".*(?=.)", "**");
  531. Map<String, Object> map = new HashMap<>();
  532. map.put("id", user.getId());
  533. map.put("avatar", user.getAvatar());
  534. map.put("phone", user.getPhone().replaceAll("(?<=.{3}).*(?=.{4})", "**"));
  535. map.put("realName", realName);
  536. return map;
  537. }
  538. public Map<String, Object> searchByPhoneAdmin(String phoneStr) {
  539. List<String> phone = Arrays.stream(phoneStr.replaceAll("\n", " ")
  540. .replaceAll("\r\n", " ")
  541. .split(" "))
  542. .map(String::trim)
  543. .filter(s -> !StringUtils.isEmpty(s))
  544. .collect(Collectors.toList());
  545. List<User> users = userRepo.findByPhoneInAndDelFalse(phone);
  546. Map<String, Object> map = new HashMap<>();
  547. map.put("users", users);
  548. List<String> notFound = phone.stream().filter(p -> users.stream().noneMatch(u -> p.equals(u.getPhone())))
  549. .collect(Collectors.toList());
  550. map.put("notFound", notFound);
  551. return map;
  552. }
  553. public void addBankCard(Long userId, String bankNo, String phone, String code) throws BaseAdaPayException {
  554. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  555. IdentityAuth identityAuth = identityAuthRepo
  556. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
  557. .orElseThrow(new BusinessException("用户未认证"));
  558. if (identityAuth.isOrg()) {
  559. //throw new BusinessException("企业认证用户请绑定对公账户");
  560. }
  561. if (!StringUtils.isBlank(user.getSettleAccountId())) {
  562. throw new BusinessException("此账号已绑定");
  563. }
  564. BankValidate bankValidate = BankUtils.validate(bankNo);
  565. if (!bankValidate.isValidated()) {
  566. throw new BusinessException("暂不支持此卡");
  567. }
  568. smsService.verify(phone, code);
  569. // adapayMerchantService.createMemberForAll(userId.toString(), user.getPhone(), identityAuth.getRealName(), identityAuth.getIdNo());
  570. // user.setMemberId(user.getId().toString());
  571. // save(user);
  572. //
  573. // String accountId = adapayMerchantService.createSettleAccountForAll
  574. // (user.getMemberId(), identityAuth.getRealName(),
  575. // identityAuth.getIdNo(), phone, bankNo);
  576. // user.setSettleAccountId(Optional.ofNullable(accountId).orElse("1"));
  577. // save(user);
  578. user.setMemberId(user.getId().toString());
  579. user.setSettleAccountId("1");
  580. save(user);
  581. userBankCardRepo.save(UserBankCard.builder()
  582. .bank(bankValidate.getBank())
  583. .bankName(bankValidate.getBankName())
  584. .bankNo(bankNo)
  585. .cardType(bankValidate.getCardType())
  586. .cardTypeDesc(bankValidate.getCardTypeDesc())
  587. .userId(userId)
  588. .phone(phone)
  589. .realName(identityAuth.getRealName())
  590. .idNo(identityAuth.getIdNo())
  591. .build());
  592. userBalanceRepo.unlock(userId);
  593. }
  594. public void removeBankCard(Long userId) throws BaseAdaPayException {
  595. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  596. // if (StringUtils.isNotBlank(user.getSettleAccountId()) && StringUtils.isNotBlank(user.getMemberId())) {
  597. // adapayMerchantService.delSettleAccountForAll(user.getMemberId());
  598. // user.setSettleAccountId(null);
  599. // save(user);
  600. // userBankCardRepo.deleteByUserId(userId);
  601. // cacheService.clearUserMy(userId);
  602. // } else {
  603. // throw new BusinessException("未绑定");
  604. // }
  605. user.setSettleAccountId(null);
  606. save(user);
  607. userBankCardRepo.deleteByUserId(userId);
  608. cacheService.clearUserMy(userId);
  609. }
  610. public void removeAuth(Long userId) {
  611. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  612. if (user.getAuthStatus() == AuthStatus.SUCCESS) {
  613. user.setAuthStatus(AuthStatus.NOT_AUTH);
  614. save(user);
  615. identityAuthRepo.deleteAll(identityAuthRepo.findByUserIdAndDelFalse(userId));
  616. cacheService.clearUserMy(userId);
  617. }
  618. }
  619. public Map<String, Object> batchRegister(String phones, String defaultPassword) {
  620. List<String> exist = new ArrayList<>();
  621. List<String> err = new ArrayList<>();
  622. List<String> success = new ArrayList<>();
  623. Arrays.stream(phones.replaceAll(",", " ")
  624. .replaceAll(",", " ")
  625. .replaceAll("\n", " ")
  626. .replaceAll("\r\n", " ")
  627. .split(" ")).forEach(phone -> {
  628. if (userRepo.findByPhoneAndDelFalse(phone).isPresent()) {
  629. exist.add(phone);
  630. } else {
  631. if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
  632. err.add(phone);
  633. } else {
  634. try {
  635. String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
  636. User user = create(UserRegister.builder()
  637. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  638. .username(name)
  639. .nickname(name)
  640. .password(defaultPassword)
  641. .avatar(Constants.DEFAULT_AVATAR)
  642. .phone(phone)
  643. .build());
  644. success.add(phone);
  645. } catch (Exception e) {
  646. log.error("注册失败", e);
  647. err.add(phone);
  648. }
  649. }
  650. }
  651. });
  652. Map<String, Object> map = new HashMap<>();
  653. map.put("exist", exist);
  654. map.put("error", err);
  655. map.put("success", success);
  656. return map;
  657. }
  658. public Map<String, Object> invite(PageQuery pageQuery) {
  659. Page<User> all = this.all(pageQuery).toPage();
  660. List<Long> userIds = all.map(User::getId).getContent();
  661. List<TokenHistory> page = tokenHistoryRepo.userBuy(userIds);
  662. Map<Long, BigDecimal> buy = page.stream()
  663. .collect(Collectors.groupingBy(TokenHistory::getToUserId,
  664. Collectors.mapping(TokenHistory::getPrice,
  665. Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
  666. Page<InvitePhoneDTO> users = all.map(user -> {
  667. InvitePhoneDTO dto = new InvitePhoneDTO(user);
  668. dto.setTotal(buy.get(user.getId()) == null ? BigDecimal.ZERO : buy.get(user.getId()));
  669. return dto;
  670. });
  671. BigDecimal total = buy.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
  672. Map<String, Object> map = new HashMap<>();
  673. map.put("user", users);
  674. map.put("total", total);
  675. return map;
  676. }
  677. @Async
  678. public void checkSettleAccountAsync() {
  679. checkSettleAccount();
  680. }
  681. public void checkSettleAccount() {
  682. List<User> list = userRepo.findBySettleAccountIdIsNotNull();
  683. AtomicInteger count = new AtomicInteger();
  684. list.forEach(user -> {
  685. try {
  686. Thread.sleep(500);
  687. IdentityAuth identityAuth = identityAuthRepo
  688. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(user.getId(), AuthStatus.SUCCESS)
  689. .orElseThrow(new BusinessException("用户未认证"));
  690. UserBankCard userBankCard = userBankCardRepo.findByUserId(user.getId()).stream().findAny()
  691. .orElseThrow(new BusinessException("未绑卡"));
  692. adapayMerchantService.createMemberForAll(
  693. user.getId().toString(), Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()),
  694. identityAuth.getRealName(), identityAuth.getIdNo());
  695. adapayMerchantService.createSettleAccountForAll(
  696. user.getId().toString(), identityAuth.getRealName(),
  697. identityAuth.getIdNo(), Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()),
  698. userBankCard.getBankNo());
  699. userBankCard.setPhone(Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()));
  700. userBankCardRepo.save(userBankCard);
  701. } catch (Exception e) {
  702. user.setSettleAccountId(null);
  703. save(user);
  704. userBankCardRepo.deleteByUserId(user.getId());
  705. }
  706. count.getAndIncrement();
  707. log.info("checkSettleAccount {}/{}", count.get(), list.size());
  708. });
  709. }
  710. @Cacheable(value = "myUserInfo", key = "#id")
  711. public User my(Long id) {
  712. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  713. user.setPassword(null);
  714. user.setTradeCode(null);
  715. return user;
  716. }
  717. public Page<Minter> toMinterDTO(Page<User> users) {
  718. List<User> origins = users.getContent();
  719. List<Minter> minters = new ArrayList<>();
  720. origins.forEach(user -> {
  721. Minter minter = Minter.builder()
  722. .id(user.getId())
  723. .name(user.getNickname())
  724. .avatar(user.getAvatar())
  725. .build();
  726. minters.add(minter);
  727. });
  728. return new PageImpl<>(minters, users.getPageable(), users.getTotalElements());
  729. }
  730. @Async
  731. public List<User> scanWeakPassword() {
  732. String[] weakPass = new String[]{
  733. "000000", "111111", "11111111", "112233", "123123", "123321", "123456", "12345678", "654321", "666666",
  734. "888888", "abcdef", "abcabc", "abc123", "a1b2c3", "aaa111", "123qwe", "qwerty", "qweasd", "admin",
  735. "password", "p@ssword", "passwd", "iloveyou", "5201314", "asdfghjkl", "66666666", "88888888"};
  736. boolean hasNext = true;
  737. int pageNum = 0;
  738. List<User> list = new ArrayList<>();
  739. while (hasNext) {
  740. Page<User> page = userRepo.findAll((Specification<User>) (root, query, criteriaBuilder) ->
  741. criteriaBuilder.isNotNull(root.get("password")), PageRequest.of(pageNum++, 200, Sort.by("id")));
  742. page.getContent().parallelStream().forEach(user -> {
  743. BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
  744. boolean match = false;
  745. for (String pass : weakPass) {
  746. if (encoder.matches(pass, user.getPassword())) {
  747. match = true;
  748. log.info("检测到弱密码userId={}, pass={}", user.getId(), pass);
  749. weakPassRepo.save(new WeakPass(user.getId(), pass));
  750. user.setPassword(null);
  751. save(user);
  752. redisTemplate.opsForValue().set(RedisKeys.JWT_TOKEN + user.getId(), "1");
  753. break;
  754. }
  755. }
  756. if (match) {
  757. list.add(user);
  758. }
  759. });
  760. hasNext = page.hasNext();
  761. }
  762. return list;
  763. }
  764. public List<InvitorDTO> findInviteOrderByCount(Long collectionId) {
  765. redisTemplate.opsForValue().get(RedisKeys.INVITOR_LIST + collectionId);
  766. List<InvitorDTO> dtos;
  767. dtos = JSONObject.parseArray((String) redisTemplate.opsForValue()
  768. .get(RedisKeys.INVITOR_LIST + collectionId), InvitorDTO.class);
  769. if (dtos == null) {
  770. dtos = new ArrayList<>();
  771. List<Object[]> objects = userRepo.customSearch(collectionId);
  772. for (Object[] object : objects) {
  773. InvitorDTO invitorDTO = new InvitorDTO((BigInteger) object[0], (String) object[1], (BigInteger) object[2]);
  774. dtos.add(invitorDTO);
  775. }
  776. redisTemplate.opsForValue()
  777. .set(RedisKeys.INVITOR_LIST + collectionId, JSONObject.toJSONString(dtos), Duration
  778. .ofSeconds(60 * 10));
  779. }
  780. return dtos;
  781. }
  782. public InvitorDetailDTO findMyInviteRecord(Long userId, Long collectionId) {
  783. InvitorDetailDTO result = new InvitorDetailDTO();
  784. // if (!SecurityUtils.getAuthenticatedUser().getId().equals(userId)) {
  785. // throw new BusinessException("无法查询他人邀请记录");
  786. // }
  787. List<InvitorDTO> invitorDTOS = findInviteOrderByCount(collectionId);
  788. InvitorDTO dto = invitorDTOS.stream()
  789. .filter(invitorDTO -> invitorDTO.getUserId().equals(BigInteger.valueOf(userId)))
  790. .findFirst().orElse(null);
  791. if (dto != null) {
  792. result.setIndex(invitorDTOS.indexOf(dto) + 1);
  793. result.setUserId(BigInteger.valueOf(userId));
  794. result.setNickName(dto.getNickName());
  795. if (result.getIndex() != 1) {
  796. result.setLastCount(invitorDTOS.get(invitorDTOS.indexOf(dto) - 1).getCount());
  797. }
  798. } else {
  799. result.setUserId(BigInteger.valueOf(userId));
  800. result.setNickName(SecurityUtils.getAuthenticatedUser().getNickname());
  801. }
  802. List<InvitedUserDTO> invitedUserDTOS = userRepo.findInvitedDTO(collectionId, userId);
  803. result.setInvitedUserDTOS(invitedUserDTOS);
  804. result.setCount(BigInteger.valueOf(invitedUserDTOS.size()));
  805. return result;
  806. }
  807. public void enableWallet(Long userId) {
  808. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  809. if (user.isWalletEnabled()) {
  810. return;
  811. }
  812. if (!sysConfigService.getBoolean("enable_wallet")) {
  813. throw new BusinessException("绿魔卡功能暂未开启");
  814. }
  815. IdentityAuth identityAuth = identityAuthRepo.findByUserId(userId).stream().findFirst().orElse(null);
  816. if (identityAuth == null) {
  817. throw new BusinessException("请先完成实名认证");
  818. }
  819. // long age = ChronoUnit.YEARS.between(LocalDate.parse(identityAuth.getIdNo().substring(6, 14),
  820. // DateTimeFormatter.ofPattern("yyyyMMdd")), LocalDate.now());
  821. // if (!((age >= 22 && age <= 55))) {
  822. // throw new BusinessException("仅22至55周岁藏家可申请绿魔卡");
  823. // }
  824. // BigDecimal amount = sysConfigService.getBigDecimal("wallet_enable_amount");
  825. // if (Optional.ofNullable(orderRepo.sumUserPrice(userId)).orElse(BigDecimal.ZERO).compareTo(amount) < 0) {
  826. // throw new BusinessException("申请绿魔卡需满" + amount + "绿洲石");
  827. // }
  828. user.setWalletEnabled(true);
  829. save(user);
  830. }
  831. }