UserService.java 40 KB

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