UserService.java 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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 cn.hutool.core.convert.Convert;
  7. import com.alibaba.fastjson.JSON;
  8. import com.alibaba.fastjson.JSONObject;
  9. import com.alipay.api.AlipayApiException;
  10. import com.alipay.api.AlipayClient;
  11. import com.alipay.api.request.AlipayUserCertifyOpenCertifyRequest;
  12. import com.alipay.api.request.AlipayUserCertifyOpenInitializeRequest;
  13. import com.alipay.api.request.AlipayUserCertifyOpenQueryRequest;
  14. import com.alipay.api.response.AlipayUserCertifyOpenCertifyResponse;
  15. import com.alipay.api.response.AlipayUserCertifyOpenInitializeResponse;
  16. import com.alipay.api.response.AlipayUserCertifyOpenQueryResponse;
  17. import com.huifu.adapay.core.exception.BaseAdaPayException;
  18. import com.izouma.nineth.TokenHistory;
  19. import com.izouma.nineth.config.Constants;
  20. import com.izouma.nineth.config.GeneralProperties;
  21. import com.izouma.nineth.config.RedisKeys;
  22. import com.izouma.nineth.domain.Collection;
  23. import com.izouma.nineth.domain.*;
  24. import com.izouma.nineth.dto.*;
  25. import com.izouma.nineth.dto.oasis.OasisLoginDTO;
  26. import com.izouma.nineth.enums.AssetStatus;
  27. import com.izouma.nineth.enums.AuthStatus;
  28. import com.izouma.nineth.enums.AuthorityName;
  29. import com.izouma.nineth.enums.HeatType;
  30. import com.izouma.nineth.event.RegisterEvent;
  31. import com.izouma.nineth.exception.BusinessException;
  32. import com.izouma.nineth.repo.*;
  33. import com.izouma.nineth.security.Authority;
  34. import com.izouma.nineth.security.JwtTokenUtil;
  35. import com.izouma.nineth.security.JwtUserFactory;
  36. import com.izouma.nineth.service.sms.SmsService;
  37. import com.izouma.nineth.service.storage.StorageService;
  38. import com.izouma.nineth.utils.*;
  39. import lombok.AllArgsConstructor;
  40. import lombok.extern.slf4j.Slf4j;
  41. import me.chanjar.weixin.common.error.WxErrorException;
  42. import me.chanjar.weixin.mp.api.WxMpService;
  43. import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
  44. import me.chanjar.weixin.mp.bean.result.WxMpUser;
  45. import org.apache.commons.lang3.ObjectUtils;
  46. import org.apache.commons.lang3.RandomStringUtils;
  47. import org.apache.commons.lang3.StringUtils;
  48. import org.apache.rocketmq.spring.core.RocketMQTemplate;
  49. import org.springframework.beans.BeanUtils;
  50. import org.springframework.cache.annotation.CacheEvict;
  51. import org.springframework.cache.annotation.Cacheable;
  52. import org.springframework.data.domain.Page;
  53. import org.springframework.data.domain.PageImpl;
  54. import org.springframework.data.domain.PageRequest;
  55. import org.springframework.data.domain.Sort;
  56. import org.springframework.data.jpa.domain.Specification;
  57. import org.springframework.data.redis.core.RedisTemplate;
  58. import org.springframework.scheduling.annotation.Async;
  59. import org.springframework.scheduling.annotation.Scheduled;
  60. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  61. import org.springframework.security.crypto.password.PasswordEncoder;
  62. import org.springframework.stereotype.Service;
  63. import javax.persistence.criteria.Predicate;
  64. import java.math.BigDecimal;
  65. import java.math.BigInteger;
  66. import java.net.URLEncoder;
  67. import java.nio.charset.StandardCharsets;
  68. import java.text.SimpleDateFormat;
  69. import java.time.Duration;
  70. import java.time.LocalDateTime;
  71. import java.util.*;
  72. import java.util.concurrent.atomic.AtomicInteger;
  73. import java.util.regex.Pattern;
  74. import java.util.stream.Collectors;
  75. @Service
  76. @Slf4j
  77. @AllArgsConstructor
  78. public class UserService {
  79. private UserRepo userRepo;
  80. private WxMaService wxMaService;
  81. private WxMpService wxMpService;
  82. private SmsService smsService;
  83. private StorageService storageService;
  84. private JwtTokenUtil jwtTokenUtil;
  85. private FollowService followService;
  86. private FollowRepo followRepo;
  87. private IdentityAuthRepo identityAuthRepo;
  88. private SysConfigService sysConfigService;
  89. private UserBankCardRepo userBankCardRepo;
  90. private InviteRepo inviteRepo;
  91. private CacheService cacheService;
  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 HeatInfoRepo heatInfoRepo;
  102. private ShowroomRepo showroomRepo;
  103. private TradingAccountRepo tradingAccountRepo;
  104. private AlipayClient alipayClient;
  105. private SnowflakeIdWorker snowflakeIdWorker;
  106. private FaceAuthRepo faceAuthRepo;
  107. private AuctionPassRecordRepo auctionPassRecordRepo;
  108. private AssetRepo assetRepo;
  109. private ShowCollectionRepo showCollectionRepo;
  110. private ShowroomService showroomService;
  111. private NewsLikeRepo newsLikeRepo;
  112. private UserPropertyRepo userPropertyRepo;
  113. private RockRecordRepo rockRecordRepo;
  114. public User update(User user) {
  115. if (!SecurityUtils.hasRole(AuthorityName.ROLE_ADMIN)) {
  116. if (!SecurityUtils.getAuthenticatedUser().getId().equals(user.getId())) {
  117. throw new BusinessException("无权限");
  118. }
  119. }
  120. User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
  121. ObjUtils.merge(orig, user);
  122. orig = save(orig);
  123. userRepo.updateAssetMinter(orig.getId());
  124. userRepo.updateAssetOwner(orig.getId());
  125. userRepo.updateCollectionMinter(orig.getId());
  126. userRepo.updateCollectionOwner(orig.getId());
  127. userRepo.updateOrderMinter(orig.getId());
  128. userRepo.updateHistoryFromUser(orig.getId());
  129. userRepo.updateHistoryToUser(orig.getId());
  130. userRepo.updateShowroomToUser(orig.getId());
  131. cacheService.clearCollection();
  132. return orig;
  133. }
  134. public User save(User user) {
  135. if (user.getId() != null) {
  136. cacheService.clearUserMy(user.getId());
  137. cacheService.clearUser(user.getId());
  138. }
  139. return userRepo.save(user);
  140. }
  141. public User update(Long userId, String nickname, String avatar, String sex, String bg, String intro,
  142. Boolean useCollectionPic, Boolean riskWarning, Integer level, Boolean isPublicShow) {
  143. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  144. if (StringUtils.isNotBlank(nickname)) {
  145. if (!nickname.equals(user.getNickname())) {
  146. if (!contentAuditService.auditText(nickname)) {
  147. throw new BusinessException("昵称包含非法内容");
  148. }
  149. }
  150. user.setNickname(nickname);
  151. }
  152. if (StringUtils.isNotBlank(avatar)) {
  153. user.setAvatar(avatar);
  154. }
  155. if (StringUtils.isNotBlank(sex)) {
  156. user.setSex(sex);
  157. }
  158. if (StringUtils.isNotBlank(bg)) {
  159. user.setBg(bg);
  160. }
  161. if (StringUtils.isNotBlank(intro)) {
  162. if (!intro.equals(user.getIntro())) {
  163. if (!contentAuditService.auditText(nickname)) {
  164. throw new BusinessException("简介包含非法内容");
  165. }
  166. }
  167. user.setIntro(intro);
  168. }
  169. if (useCollectionPic != null) {
  170. user.setUseCollectionPic(useCollectionPic);
  171. }
  172. if (riskWarning != null) {
  173. user.setRiskWarning(riskWarning);
  174. }
  175. if (level != null) {
  176. user.setLevel(level);
  177. }
  178. if (isPublicShow != null) {
  179. user.setIsPublicShow(isPublicShow);
  180. }
  181. user = save(user);
  182. userRepo.updateAssetMinter(userId);
  183. userRepo.updateAssetOwner(userId);
  184. userRepo.updateCollectionMinter(userId);
  185. userRepo.updateCollectionOwner(userId);
  186. userRepo.updateOrderMinter(userId);
  187. userRepo.updateHistoryFromUser(userId);
  188. userRepo.updateHistoryToUser(userId);
  189. userRepo.updateShowroomToUser(userId);
  190. return user;
  191. }
  192. @Cacheable(value = "userList", key = "#pageQuery.hashCode()")
  193. public PageWrapper<User> all(PageQuery pageQuery) {
  194. Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);
  195. specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
  196. List<Predicate> and = new ArrayList<>();
  197. and.add(criteriaBuilder.equal(root.get("del"), false));
  198. if (!pageQuery.getQuery().containsKey("admin")) {
  199. and.add(criteriaBuilder.equal(root.get("admin"), false));
  200. }
  201. if (pageQuery.getQuery().containsKey("hasRole")) {
  202. String roleName = (String) pageQuery.getQuery().get("hasRole");
  203. if (roleName.equals("ROLE_MINTER")) {
  204. and.add(criteriaBuilder.equal(root.get("minter"), true));
  205. } else {
  206. and.add(criteriaBuilder
  207. .isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
  208. }
  209. }
  210. if (pageQuery.getQuery().containsKey("vip")) {
  211. boolean vip = (boolean) pageQuery.getQuery().get("vip");
  212. if (vip) {
  213. and.add(criteriaBuilder.greaterThan(root.get("vipPurchase"), 0));
  214. } else {
  215. and.add(criteriaBuilder.lessThanOrEqualTo(root.get("vipPurchase"), 0));
  216. }
  217. }
  218. return criteriaBuilder.and(and.toArray(new Predicate[0]));
  219. });
  220. Page<User> page = userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
  221. return PageWrapper.of(page);
  222. }
  223. public User create(UserRegister userRegister) {
  224. User user = new User();
  225. BeanUtils.copyProperties(userRegister, user);
  226. user.setShareRatio(sysConfigService.getBigDecimal("share_ratio"));
  227. user.setAuthStatus(AuthStatus.NOT_AUTH);
  228. if (StringUtils.isNotBlank(userRegister.getPassword())) {
  229. checkPasswordStrength(userRegister.getPassword());
  230. user.setPassword(passwordEncoder.encode(userRegister.getPassword()));
  231. }
  232. return save(user);
  233. }
  234. public User phoneRegister(String phone, String code, String password, String inviteCode, Long invitor,
  235. Long collectionId, Long showroomId) {
  236. String name = "0x" + RandomStringUtils.randomAlphabetic(8);
  237. Invite invite = null;
  238. if (StringUtils.isNotBlank(inviteCode)) {
  239. invite = inviteRepo.findFirstByCode(inviteCode).orElse(null);
  240. }
  241. smsService.verify(phone, code);
  242. Collection collection;
  243. if (collectionId != null) {
  244. collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("无藏品"));
  245. // if (!collection.isOnShelf() || !collection.isSalable()) {
  246. // collectionId = null;
  247. // } else if (collection.isScheduleSale()) {
  248. // if (collection.getStartTime().isAfter(LocalDateTime.now())) {
  249. // collectionId = null;
  250. // }
  251. // }
  252. // 只看是否开去分享
  253. if (ObjectUtils.isEmpty(collection.getOpenQuota()) || !collection.getOpenQuota()) {
  254. collectionId = null;
  255. }
  256. }
  257. User user = create(UserRegister.builder()
  258. .username(name)
  259. .nickname(name)
  260. .password(password)
  261. .avatar(Constants.DEFAULT_AVATAR)
  262. .phone(phone)
  263. .invitorPhone(Optional.ofNullable(invite).map(Invite::getPhone).orElse(null))
  264. .invitorName(Optional.ofNullable(invite).map(Invite::getName).orElse(null))
  265. .inviteCode(Optional.ofNullable(invite).map(Invite::getCode).orElse(null))
  266. .collectionInvitor(invitor)
  267. .collectionId(collectionId)
  268. .build());
  269. if (invite != null) {
  270. inviteRepo.increaseNum(invite.getId());
  271. }
  272. if (ObjectUtils.isNotEmpty(showroomId)) {
  273. //通过展厅的注册数量
  274. int weight = sysConfigService.getInt("heat_register_weight");
  275. heatInfoRepo.save(HeatInfo.builder()
  276. .showroomId(showroomId)
  277. .userId(user.getId())
  278. .type(HeatType.REGISTER)
  279. .value(weight)
  280. .build());
  281. showroomRepo.addHeatAndRegister(showroomId, weight, 1);
  282. }
  283. return user;
  284. }
  285. public String mqRegister(String phone, String code, String password, String inviteCode, Long invitor,
  286. Long collectionId, Long showroomId) {
  287. rocketMQTemplate.convertAndSend(generalProperties.getRegisterTopic(),
  288. new RegisterEvent(phone, code, password, inviteCode, invitor, collectionId, showroomId));
  289. return phone;
  290. }
  291. public Object getRegisterResult(String phone) {
  292. return redisTemplate.opsForValue().get("register::" + phone);
  293. }
  294. public void del(Long id) {
  295. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  296. user.setDel(true);
  297. if (StringUtils.isNoneEmpty(user.getOpenId())) {
  298. user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
  299. }
  300. if (StringUtils.isNoneEmpty(user.getPhone())) {
  301. user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
  302. }
  303. save(user);
  304. //删除实名认证
  305. identityAuthRepo.softDeleteByUserId(id);
  306. }
  307. public User loginByPhone(String phone, String code) {
  308. User user = userRepo.findByPhoneAndDelFalse(phone).orElse(null);
  309. smsService.verify(phone, code);
  310. if (user == null) {
  311. String name = "0x" + RandomStringUtils.randomAlphabetic(8);
  312. user = create(UserRegister.builder()
  313. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  314. .username(name)
  315. .nickname(name)
  316. .avatar(Constants.DEFAULT_AVATAR)
  317. .phone(phone)
  318. .build());
  319. }
  320. return user;
  321. }
  322. public User loginByPhonePwd(String phone, String password) {
  323. if (StringUtils.isEmpty(phone)) {
  324. throw new BusinessException("手机号错误");
  325. }
  326. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  327. if (StringUtils.isEmpty(user.getPassword())) {
  328. throw new BusinessException("账号或密码错误");
  329. }
  330. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  331. !passwordEncoder.matches(password, user.getPassword())) {
  332. throw new BusinessException("账号或密码错误");
  333. }
  334. return user;
  335. }
  336. public User loginByUsernamePwd(String username, String password) {
  337. if (StringUtils.isEmpty(username)) {
  338. throw new BusinessException("用户名错误");
  339. }
  340. User user = userRepo.findByUsernameAndDelFalse(username).orElseThrow(new BusinessException("账号或密码错误"));
  341. if (StringUtils.isEmpty(user.getPassword())
  342. || !passwordEncoder.matches(password, user.getPassword())) {
  343. throw new BusinessException("账号或密码错误");
  344. }
  345. return user;
  346. }
  347. public User loginMp(String code) throws WxErrorException {
  348. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  349. WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
  350. User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
  351. if (user == null) {
  352. String name = "0x" + RandomStringUtils.randomAlphabetic(8);
  353. user = User.builder()
  354. .username(name)
  355. .nickname(name)
  356. .avatar(wxMpUser.getHeadImgUrl())
  357. .sex(wxMpUser.getSexDesc())
  358. .country(wxMpUser.getCountry())
  359. .province(wxMpUser.getProvince())
  360. .city(wxMpUser.getCity())
  361. .openId(wxMpUser.getOpenId())
  362. .language(wxMpUser.getLanguage())
  363. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  364. .authStatus(AuthStatus.NOT_AUTH)
  365. .build();
  366. save(user);
  367. }
  368. return user;
  369. }
  370. public String code2openId(String code) throws WxErrorException {
  371. WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
  372. return wxMpService.oauth2getUserInfo(accessToken, null).getOpenId();
  373. }
  374. public User loginMa(String code) {
  375. try {
  376. WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
  377. String openId = result.getOpenid();
  378. String sessionKey = result.getSessionKey();
  379. User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
  380. ;
  381. if (userInfo != null) {
  382. return userInfo;
  383. }
  384. String name = "0x" + RandomStringUtils.randomAlphabetic(8);
  385. userInfo = User.builder()
  386. .username(name)
  387. .nickname(name)
  388. .openId(openId)
  389. .avatar(Constants.DEFAULT_AVATAR)
  390. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  391. .authStatus(AuthStatus.NOT_AUTH)
  392. .build();
  393. userInfo = save(userInfo);
  394. return userInfo;
  395. } catch (WxErrorException e) {
  396. e.printStackTrace();
  397. }
  398. throw new BusinessException("登录失败");
  399. }
  400. public User getMaUserInfo(String sessionKey, String rawData, String signature,
  401. String encryptedData, String iv) {
  402. // 用户信息校验
  403. if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
  404. throw new BusinessException("获取用户信息失败");
  405. }
  406. // 解密用户信息
  407. WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
  408. User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
  409. String avatarUrl = Constants.DEFAULT_AVATAR;
  410. try {
  411. String path = "image/avatar/" +
  412. new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
  413. RandomStringUtils.randomAlphabetic(8) +
  414. ".jpg";
  415. avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
  416. } catch (Exception e) {
  417. log.error("获取头像失败", e);
  418. }
  419. if (user == null) {
  420. user = User.builder()
  421. .username(UUID.randomUUID().toString())
  422. .nickname(wxUserInfo.getNickName())
  423. .openId(wxUserInfo.getOpenId())
  424. .avatar(avatarUrl)
  425. .sex(wxUserInfo.getGender())
  426. .country(wxUserInfo.getCountry())
  427. .province(wxUserInfo.getProvince())
  428. .city(wxUserInfo.getCity())
  429. .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
  430. .build();
  431. user = save(user);
  432. } else {
  433. user.setAvatar(avatarUrl);
  434. user.setNickname(wxUserInfo.getNickName());
  435. user.setSex(wxUserInfo.getGender());
  436. user.setCountry(wxUserInfo.getCountry());
  437. user.setProvince(wxUserInfo.getProvince());
  438. user.setCity(wxUserInfo.getCity());
  439. user = save(user);
  440. }
  441. return user;
  442. }
  443. public String setPassword(Long userId, String password) {
  444. checkPasswordStrength(password);
  445. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  446. user.setPassword(passwordEncoder.encode(password));
  447. user = save(user);
  448. return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
  449. }
  450. public String setPassword(Long userId, String code, String password) {
  451. checkPasswordStrength(password);
  452. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  453. smsService.verify(user.getPhone(), code);
  454. return setPassword(userId, password);
  455. }
  456. public String forgotPassword(String phone, String password, String code) {
  457. checkPasswordStrength(password);
  458. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("手机号未注册"));
  459. smsService.verify(user.getPhone(), code);
  460. return setPassword(user.getId(), password);
  461. }
  462. public static void checkPasswordStrength(String password) {
  463. if (StringUtils.isBlank(password)) throw new BusinessException("密码不能为空");
  464. if (!Pattern.matches("^[a-zA-Z0-9!@#$%^&*]+$", password)) throw new BusinessException("密码含非法字符");
  465. int upper = 0;
  466. int lower = 0;
  467. int digit = 0;
  468. int special = 0;
  469. char ch;
  470. for (int i = 0; i < password.length(); i++) {
  471. ch = password.charAt(i);
  472. if (Character.isUpperCase(ch))
  473. upper++;
  474. else if (Character.isLowerCase(ch))
  475. lower++;
  476. else if (Character.isDigit(ch))
  477. digit++;
  478. else {
  479. if (ch == '<' || ch == '>') {
  480. throw new BusinessException("密码包含非法字符");
  481. } else
  482. special++;
  483. }
  484. }
  485. if (upper > 0 && lower > 0 && digit > 0 && password.length() >= 8) {
  486. return;
  487. }
  488. throw new BusinessException("密码长度至少为8位,且必须包含大小写字母和数字");
  489. }
  490. public void bindPhone(Long userId, String phone) {
  491. User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
  492. if (StringUtils.isNoneEmpty(user.getPhone())) {
  493. throw new BusinessException("该账号已绑定手机");
  494. }
  495. userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
  496. if (!user1.getId().equals(userId)) {
  497. throw new BusinessException("该手机号已绑定其他账号");
  498. }
  499. });
  500. user.setPhone(phone);
  501. save(user);
  502. }
  503. public UserDTO toDTO(User user) {
  504. return toDTO(user, true);
  505. }
  506. public UserDTO toDTO(User user, boolean join) {
  507. UserDTO userDTO = new UserDTO();
  508. BeanUtils.copyProperties(user, userDTO);
  509. if (user.getAuthorities() != null) {
  510. userDTO.setAuthorities(new HashSet<>(user.getAuthorities()));
  511. }
  512. if (join) {
  513. if (SecurityUtils.getAuthenticatedUser() != null) {
  514. userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
  515. }
  516. }
  517. return userDTO;
  518. }
  519. public List<UserDTO> toDTO(List<User> users) {
  520. List<Follow> follows = new ArrayList<>();
  521. if (SecurityUtils.getAuthenticatedUser() != null) {
  522. follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
  523. }
  524. return users.stream().parallel().map(user -> {
  525. UserDTO dto = toDTO(user, false);
  526. if (!follows.isEmpty()) {
  527. dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
  528. }
  529. return dto;
  530. }).collect(Collectors.toList());
  531. }
  532. public Page<UserDTO> toDTO(Page<User> users) {
  533. List<UserDTO> userDTOS = toDTO(users.getContent());
  534. return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
  535. }
  536. @CacheEvict(value = "user", allEntries = true)
  537. public void setTradeCode(Long userId, String token, String tradeCode) {
  538. String phone = smsService.verifyToken(token);
  539. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  540. if (!StringUtils.equals(phone, user.getPhone())) {
  541. throw new BusinessException("验证码无效");
  542. }
  543. user.setTradeCode(passwordEncoder.encode(tradeCode));
  544. save(user);
  545. }
  546. public void verifyTradeCode(Long userId, String tradeCode) {
  547. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  548. if (!passwordEncoder.matches(tradeCode, user.getTradeCode())) {
  549. throw new BusinessException("交易密码错误");
  550. }
  551. }
  552. public Map<String, Object> searchByPhone(String phone) {
  553. if (AuthStatus.SUCCESS != SecurityUtils.getAuthenticatedUser().getAuthStatus()) {
  554. throw new BusinessException("实名认证后才能赠送");
  555. }
  556. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("用户不存在或未认证"));
  557. if (AuthStatus.SUCCESS != user.getAuthStatus()) {
  558. throw new BusinessException("用户不存在或未认证");
  559. }
  560. String realName = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(
  561. user.getId(), AuthStatus.SUCCESS)
  562. .map(IdentityAuth::getRealName).orElse("").replaceAll(".*(?=.)", "**");
  563. Map<String, Object> map = new HashMap<>();
  564. map.put("id", user.getId());
  565. map.put("avatar", user.getAvatar());
  566. map.put("phone", user.getPhone().replaceAll("(?<=.{3}).*(?=.{4})", "**"));
  567. map.put("realName", realName);
  568. return map;
  569. }
  570. public Map<String, Object> searchByPhoneAdmin(String phoneStr) {
  571. List<String> phone = Arrays.stream(phoneStr.replaceAll("\n", " ")
  572. .replaceAll("\r\n", " ")
  573. .split(" "))
  574. .map(String::trim)
  575. .filter(s -> !StringUtils.isEmpty(s))
  576. .collect(Collectors.toList());
  577. List<User> users = userRepo.findByPhoneInAndDelFalse(phone);
  578. Map<String, Object> map = new HashMap<>();
  579. map.put("users", users);
  580. List<String> notFound = phone.stream().filter(p -> users.stream().noneMatch(u -> p.equals(u.getPhone())))
  581. .collect(Collectors.toList());
  582. map.put("notFound", notFound);
  583. return map;
  584. }
  585. public void addBankCard(Long userId, String bankNo, String phone, String code) throws BaseAdaPayException {
  586. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  587. IdentityAuth identityAuth = identityAuthRepo
  588. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
  589. .orElseThrow(new BusinessException("用户未认证"));
  590. if (identityAuth.isOrg()) {
  591. //throw new BusinessException("企业认证用户请绑定对公账户");
  592. }
  593. if (!StringUtils.isBlank(user.getSettleAccountId())) {
  594. throw new BusinessException("此账号已绑定");
  595. }
  596. BankValidate bankValidate = BankUtils.validate(bankNo);
  597. if (!bankValidate.isValidated()) {
  598. throw new BusinessException("暂不支持此卡");
  599. }
  600. smsService.verify(phone, code);
  601. // adapayMerchantService.createMemberForAll(userId.toString(), user.getPhone(), identityAuth.getRealName(), identityAuth.getIdNo());
  602. // user.setMemberId(user.getId().toString());
  603. // save(user);
  604. //
  605. // String accountId = adapayMerchantService.createSettleAccountForAll
  606. // (user.getMemberId(), identityAuth.getRealName(),
  607. // identityAuth.getIdNo(), phone, bankNo);
  608. // user.setSettleAccountId(Optional.ofNullable(accountId).orElse("1"));
  609. // save(user);
  610. user.setMemberId(user.getId().toString());
  611. user.setSettleAccountId("1");
  612. save(user);
  613. userBankCardRepo.save(UserBankCard.builder()
  614. .bank(bankValidate.getBank())
  615. .bankName(bankValidate.getBankName())
  616. .bankNo(bankNo)
  617. .cardType(bankValidate.getCardType())
  618. .cardTypeDesc(bankValidate.getCardTypeDesc())
  619. .userId(userId)
  620. .phone(phone)
  621. .realName(identityAuth.getRealName())
  622. .idNo(identityAuth.getIdNo())
  623. .build());
  624. userBalanceRepo.unlock(userId);
  625. }
  626. public void removeBankCard(Long userId) throws BaseAdaPayException {
  627. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  628. // if (StringUtils.isNotBlank(user.getSettleAccountId()) && StringUtils.isNotBlank(user.getMemberId())) {
  629. // adapayMerchantService.delSettleAccountForAll(user.getMemberId());
  630. // user.setSettleAccountId(null);
  631. // save(user);
  632. // userBankCardRepo.deleteByUserId(userId);
  633. // cacheService.clearUserMy(userId);
  634. // } else {
  635. // throw new BusinessException("未绑定");
  636. // }
  637. user.setSettleAccountId(null);
  638. save(user);
  639. userBankCardRepo.deleteByUserId(userId);
  640. cacheService.clearUserMy(userId);
  641. }
  642. public void removeAuth(Long userId) {
  643. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  644. if (user.getAuthStatus() == AuthStatus.SUCCESS) {
  645. user.setAuthStatus(AuthStatus.NOT_AUTH);
  646. save(user);
  647. identityAuthRepo.deleteAll(identityAuthRepo.findByUserIdAndDelFalse(userId));
  648. cacheService.clearUserMy(userId);
  649. }
  650. }
  651. public Map<String, Object> batchRegister(String phones, String defaultPassword) {
  652. List<String> exist = new ArrayList<>();
  653. List<String> err = new ArrayList<>();
  654. List<String> success = new ArrayList<>();
  655. Arrays.stream(phones.replaceAll(",", " ")
  656. .replaceAll(",", " ")
  657. .replaceAll("\n", " ")
  658. .replaceAll("\r\n", " ")
  659. .split(" ")).forEach(phone -> {
  660. if (userRepo.findByPhoneAndDelFalse(phone).isPresent()) {
  661. exist.add(phone);
  662. } else {
  663. if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
  664. err.add(phone);
  665. } else {
  666. try {
  667. String name = "0x" + RandomStringUtils.randomAlphabetic(8);
  668. User user = create(UserRegister.builder()
  669. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  670. .username(name)
  671. .nickname(name)
  672. .password(defaultPassword)
  673. .avatar(Constants.DEFAULT_AVATAR)
  674. .phone(phone)
  675. .build());
  676. success.add(phone);
  677. } catch (Exception e) {
  678. log.error("注册失败", e);
  679. err.add(phone);
  680. }
  681. }
  682. }
  683. });
  684. Map<String, Object> map = new HashMap<>();
  685. map.put("exist", exist);
  686. map.put("error", err);
  687. map.put("success", success);
  688. return map;
  689. }
  690. public Map<String, Object> invite(PageQuery pageQuery) {
  691. Page<User> all = this.all(pageQuery).toPage();
  692. List<Long> userIds = all.map(User::getId).getContent();
  693. // List<TokenHistory> page = tokenHistoryRepo.userBuy(userIds);
  694. // Map<Long, BigDecimal> buy = page.stream()
  695. // .collect(Collectors.groupingBy(TokenHistory::getToUserId,
  696. // Collectors.mapping(TokenHistory::getPrice,
  697. // Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
  698. Page<InvitePhoneDTO> users = all.map(user -> {
  699. InvitePhoneDTO dto = new InvitePhoneDTO(user);
  700. BigDecimal buy = rockRecordRepo.findRecordByUserIdOrderByIdDesc(user.getId());
  701. dto.setTotal(buy);
  702. return dto;
  703. });
  704. BigDecimal total = rockRecordRepo.findRecordByUserIdOrderByIdInDesc(userIds);
  705. Map<String, Object> map = new HashMap<>();
  706. map.put("user", users);
  707. map.put("total", total);
  708. return map;
  709. }
  710. @Async
  711. public void checkSettleAccountAsync() {
  712. checkSettleAccount();
  713. }
  714. public void checkSettleAccount() {
  715. List<User> list = userRepo.findBySettleAccountIdIsNotNull();
  716. AtomicInteger count = new AtomicInteger();
  717. list.forEach(user -> {
  718. try {
  719. Thread.sleep(500);
  720. IdentityAuth identityAuth = identityAuthRepo
  721. .findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(user.getId(), AuthStatus.SUCCESS)
  722. .orElseThrow(new BusinessException("用户未认证"));
  723. UserBankCard userBankCard = userBankCardRepo.findByUserId(user.getId()).stream().findAny()
  724. .orElseThrow(new BusinessException("未绑卡"));
  725. adapayMerchantService.createMemberForAll(
  726. user.getId().toString(), Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()),
  727. identityAuth.getRealName(), identityAuth.getIdNo());
  728. adapayMerchantService.createSettleAccountForAll(
  729. user.getId().toString(), identityAuth.getRealName(),
  730. identityAuth.getIdNo(), Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()),
  731. userBankCard.getBankNo());
  732. userBankCard.setPhone(Optional.ofNullable(userBankCard.getPhone()).orElse(user.getPhone()));
  733. userBankCardRepo.save(userBankCard);
  734. } catch (Exception e) {
  735. user.setSettleAccountId(null);
  736. save(user);
  737. userBankCardRepo.deleteByUserId(user.getId());
  738. }
  739. count.getAndIncrement();
  740. log.info("checkSettleAccount {}/{}", count.get(), list.size());
  741. });
  742. }
  743. @Cacheable(value = "myUserInfo", key = "#id")
  744. public User my(Long id) {
  745. User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
  746. user.setPassword(null);
  747. user.setTradeCode(null);
  748. return user;
  749. }
  750. public Page<Minter> toMinterDTO(Page<User> users) {
  751. List<User> origins = users.getContent();
  752. List<Minter> minters = new ArrayList<>();
  753. origins.forEach(user -> {
  754. Minter minter = Minter.builder()
  755. .id(user.getId())
  756. .name(user.getNickname())
  757. .avatar(user.getAvatar())
  758. .build();
  759. minters.add(minter);
  760. });
  761. return new PageImpl<>(minters, users.getPageable(), users.getTotalElements());
  762. }
  763. @Async
  764. public List<User> scanWeakPassword() {
  765. String[] weakPass = new String[]{
  766. "000000", "111111", "11111111", "112233", "123123", "123321", "123456", "12345678", "654321", "666666",
  767. "888888", "abcdef", "abcabc", "abc123", "a1b2c3", "aaa111", "123qwe", "qwerty", "qweasd", "admin",
  768. "password", "p@ssword", "passwd", "iloveyou", "5201314", "asdfghjkl", "66666666", "88888888"};
  769. boolean hasNext = true;
  770. int pageNum = 0;
  771. List<User> list = new ArrayList<>();
  772. while (hasNext) {
  773. Page<User> page = userRepo.findAll((Specification<User>) (root, query, criteriaBuilder) ->
  774. criteriaBuilder.isNotNull(root.get("password")), PageRequest.of(pageNum++, 200, Sort.by("id")));
  775. page.getContent().parallelStream().forEach(user -> {
  776. BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
  777. boolean match = false;
  778. for (String pass : weakPass) {
  779. if (encoder.matches(pass, user.getPassword())) {
  780. match = true;
  781. log.info("检测到弱密码userId={}, pass={}", user.getId(), pass);
  782. weakPassRepo.save(new WeakPass(user.getId(), pass));
  783. user.setPassword(null);
  784. save(user);
  785. redisTemplate.opsForValue().set(RedisKeys.JWT_TOKEN + user.getId(), "1");
  786. break;
  787. }
  788. }
  789. if (match) {
  790. list.add(user);
  791. }
  792. });
  793. hasNext = page.hasNext();
  794. }
  795. return list;
  796. }
  797. public List<InvitorDTO> findInviteOrderByCount(Long collectionId) {
  798. redisTemplate.opsForValue().get(RedisKeys.INVITOR_LIST + collectionId);
  799. List<InvitorDTO> dtos;
  800. dtos = JSONObject.parseArray((String) redisTemplate.opsForValue()
  801. .get(RedisKeys.INVITOR_LIST + collectionId), InvitorDTO.class);
  802. if (dtos == null) {
  803. dtos = new ArrayList<>();
  804. List<Object[]> objects = userRepo.customSearch(collectionId);
  805. for (Object[] object : objects) {
  806. InvitorDTO invitorDTO = new InvitorDTO((BigInteger) object[0], (String) object[1], (BigInteger) object[2]);
  807. dtos.add(invitorDTO);
  808. }
  809. redisTemplate.opsForValue()
  810. .set(RedisKeys.INVITOR_LIST + collectionId, JSONObject.toJSONString(dtos), Duration
  811. .ofSeconds(60 * 10));
  812. }
  813. return dtos;
  814. }
  815. public InvitorDetailDTO findMyInviteRecord(Long userId, Long collectionId) {
  816. InvitorDetailDTO result = new InvitorDetailDTO();
  817. // if (!SecurityUtils.getAuthenticatedUser().getId().equals(userId)) {
  818. // throw new BusinessException("无法查询他人邀请记录");
  819. // }
  820. List<InvitorDTO> invitorDTOS = findInviteOrderByCount(collectionId);
  821. InvitorDTO dto = invitorDTOS.stream()
  822. .filter(invitorDTO -> invitorDTO.getUserId().equals(BigInteger.valueOf(userId)))
  823. .findFirst().orElse(null);
  824. if (dto != null) {
  825. result.setIndex(invitorDTOS.indexOf(dto) + 1);
  826. result.setUserId(BigInteger.valueOf(userId));
  827. result.setNickName(dto.getNickName());
  828. if (result.getIndex() != 1) {
  829. result.setLastCount(invitorDTOS.get(invitorDTOS.indexOf(dto) - 1).getCount());
  830. }
  831. } else {
  832. result.setUserId(BigInteger.valueOf(userId));
  833. result.setNickName(SecurityUtils.getAuthenticatedUser().getNickname());
  834. }
  835. List<InvitedUserDTO> invitedUserDTOS = userRepo.findInvitedDTO(collectionId, userId);
  836. result.setInvitedUserDTOS(invitedUserDTOS);
  837. result.setCount(BigInteger.valueOf(invitedUserDTOS.size()));
  838. return result;
  839. }
  840. public void enableWallet(Long userId) {
  841. User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
  842. if (user.isWalletEnabled()) {
  843. return;
  844. }
  845. if (!sysConfigService.getBoolean("enable_wallet")) {
  846. throw new BusinessException("绿魔卡功能暂未开启");
  847. }
  848. IdentityAuth identityAuth = identityAuthRepo.findByUserId(userId).stream().findFirst().orElse(null);
  849. if (identityAuth == null) {
  850. throw new BusinessException("请先完成实名认证");
  851. }
  852. // long age = ChronoUnit.YEARS.between(LocalDate.parse(identityAuth.getIdNo().substring(6, 14),
  853. // DateTimeFormatter.ofPattern("yyyyMMdd")), LocalDate.now());
  854. // if (!((age >= 22 && age <= 55))) {
  855. // throw new BusinessException("仅22至55周岁藏家可申请绿魔卡");
  856. // }
  857. // BigDecimal amount = sysConfigService.getBigDecimal("wallet_enable_amount");
  858. // if (Optional.ofNullable(orderRepo.sumUserPrice(userId)).orElse(BigDecimal.ZERO).compareTo(amount) < 0) {
  859. // throw new BusinessException("申请绿魔卡需满" + amount + "绿洲石");
  860. // }
  861. user.setWalletEnabled(true);
  862. save(user);
  863. }
  864. public Page<CompanyDTO> companyList(PageQuery pageQuery) {
  865. Page<User> users = this.all(pageQuery).toPage();
  866. List<Map<String, Object>> companyNums = showroomRepo.countNum("COMPANY");
  867. Map<Long, Integer> showroomNum = new HashMap<>();
  868. companyNums.forEach(value -> showroomNum.put(Convert.convert(Long.class, value.get("user_id")),
  869. Convert.convert(Integer.class, value.get("num"))));
  870. List<Map<String, Object>> companyBoxNums = showroomRepo.countNum("COMPANY_BOX");
  871. Map<Long, Integer> boxNum = new HashMap<>();
  872. companyBoxNums.forEach(value -> boxNum.put(Convert.convert(Long.class, value.get("user_id")),
  873. Convert.convert(Integer.class, value.get("num"))));
  874. return users.map(user -> {
  875. CompanyDTO dto = new CompanyDTO(user);
  876. dto.setShowroomNum(showroomNum.get(user.getId()) == null ? 0 : showroomNum.get(user.getId()));
  877. dto.setBoxShowroomNum(boxNum.get(user.getId()) == null ? 0 : boxNum.get(user.getId()));
  878. return dto;
  879. });
  880. }
  881. public Object loginTrading(String phone, String password, String tradeCode) {
  882. if (StringUtils.isEmpty(phone)) {
  883. throw new BusinessException("手机号错误");
  884. }
  885. User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
  886. TradingAccount tradingAccount = tradingAccountRepo.findById(user.getId())
  887. .orElseThrow(new BusinessException("账号或密码错误"));
  888. if (StringUtils.isEmpty(user.getPassword())) {
  889. throw new BusinessException("账号或密码错误");
  890. }
  891. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  892. !passwordEncoder.matches(password, user.getPassword())) {
  893. throw new BusinessException("账号或密码错误");
  894. }
  895. if (StringUtils.isNoneEmpty(user.getPassword()) &&
  896. !passwordEncoder.matches(tradeCode, user.getTradeCode())) {
  897. throw new BusinessException("支付密码错误");
  898. }
  899. Map<String, Object> map = new HashMap<>();
  900. map.put("user", user);
  901. map.put("token", jwtTokenUtil.generateToken(JwtUserFactory.create(user)));
  902. map.put("account", tradingAccount);
  903. return map;
  904. }
  905. public Object myTrading(Long id) {
  906. User user = userRepo.findById(id).orElseThrow(new BusinessException("账号或密码错误"));
  907. TradingAccount tradingAccount = tradingAccountRepo.findById(user.getId())
  908. .orElseThrow(new BusinessException("账号或密码错误"));
  909. Map<String, Object> map = new HashMap<>();
  910. map.put("user", user);
  911. map.put("account", tradingAccount);
  912. return map;
  913. }
  914. public String prepareAliAuth(String type, Long userId, String name, String no) throws AlipayApiException {
  915. Long id = snowflakeIdWorker.nextId();
  916. AlipayUserCertifyOpenInitializeRequest request = new AlipayUserCertifyOpenInitializeRequest();
  917. JSONObject biz = new JSONObject();
  918. biz.put("outer_order_no", id + "");
  919. biz.put("biz_code", "FACE");
  920. JSONObject identity_param = new JSONObject();
  921. identity_param.put("identity_type", "CERT_INFO");
  922. identity_param.put("cert_type", type);
  923. identity_param.put("cert_name", name);
  924. identity_param.put("cert_no", no);
  925. biz.put("identity_param", identity_param);
  926. JSONObject merchant_config = new JSONObject();
  927. merchant_config.put("return_url", "alipays://platformapi/startapp?appId=20000067&url=" +
  928. URLEncoder.encode(generalProperties.getHost() + "/user/faceAuthNotify/" + id, StandardCharsets.UTF_8));
  929. biz.put("merchant_config", merchant_config);
  930. log.info(JSON.toJSONString(biz, true));
  931. request.setBizContent(biz.toJSONString());
  932. AlipayUserCertifyOpenInitializeResponse response = alipayClient.execute(request);
  933. if (response.isSuccess()) {
  934. String certifyId = response.getCertifyId();
  935. faceAuthRepo.save(FaceAuth.builder()
  936. .id(id)
  937. .userId(userId)
  938. .name(name)
  939. .idNo(no)
  940. .certifyId(certifyId)
  941. .build());
  942. return certifyId;
  943. }
  944. throw new BusinessException(response.getMsg());
  945. }
  946. public String getAliAuthUrl(String certify_id) throws AlipayApiException {
  947. AlipayUserCertifyOpenCertifyRequest request = new AlipayUserCertifyOpenCertifyRequest();
  948. JSONObject bizContentObj = new JSONObject();
  949. bizContentObj.put("certify_id", certify_id);
  950. request.setBizContent(bizContentObj.toString());
  951. AlipayUserCertifyOpenCertifyResponse response = alipayClient.pageExecute(request, "GET");
  952. if (response.isSuccess()) {
  953. return response.getBody();
  954. }
  955. throw new BusinessException(response.getMsg());
  956. }
  957. public User oneKeyLogin(String umengKey, String token) {
  958. String phone = UmengUtils.getMobile(umengKey, token);
  959. if (StringUtils.isBlank(phone)) {
  960. throw new BusinessException("登录失败,请尝试其他方式");
  961. }
  962. User user = userRepo.findByPhoneAndDelFalse(phone).orElse(null);
  963. if (user == null) {
  964. String name = "0x" + RandomStringUtils.randomAlphabetic(8);
  965. user = create(UserRegister.builder()
  966. .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
  967. .username(name)
  968. .nickname(name)
  969. .avatar(Constants.DEFAULT_AVATAR)
  970. .phone(phone)
  971. .build());
  972. }
  973. return user;
  974. }
  975. public Map<String, Object> checkFaceAuth(String certifyId) throws AlipayApiException {
  976. AlipayUserCertifyOpenQueryRequest request = new AlipayUserCertifyOpenQueryRequest();
  977. JSONObject biz = new JSONObject();
  978. biz.put("certify_id", certifyId);
  979. request.setBizContent(biz.toJSONString());
  980. AlipayUserCertifyOpenQueryResponse response = alipayClient.execute(request);
  981. Map<String, Object> map = new HashMap<>();
  982. if (response.isSuccess()) {
  983. System.out.println("调用成功");
  984. } else {
  985. System.out.println("调用失败");
  986. }
  987. return map;
  988. }
  989. public void faceAuthNotify(Long id) {
  990. faceAuthRepo.findById(id).ifPresent(faceAuth -> {
  991. try {
  992. AlipayUserCertifyOpenQueryRequest request = new AlipayUserCertifyOpenQueryRequest();
  993. JSONObject biz = new JSONObject();
  994. biz.put("certify_id", faceAuth.getCertifyId());
  995. request.setBizContent(biz.toJSONString());
  996. AlipayUserCertifyOpenQueryResponse response = alipayClient.execute(request);
  997. if (response.isSuccess()) {
  998. JSONObject res = JSONObject.parseObject(response.getBody());
  999. JSONObject data = res.getJSONObject("alipay_user_certify_open_query_response");
  1000. if (StringUtils.equals(data.getString("passed"), "T")) {
  1001. User user = userRepo.findById(faceAuth.getUserId()).orElse(null);
  1002. if (user != null) {
  1003. IdentityAuth identityAuth = identityAuthRepo.save(IdentityAuth.builder()
  1004. .userId(user.getId())
  1005. .idNo(faceAuth.getIdNo())
  1006. .realName(faceAuth.getName())
  1007. .status(AuthStatus.SUCCESS)
  1008. .build());
  1009. identityAuthRepo.deleteDuplicated(user.getId(), identityAuth.getId());
  1010. user.setAuthStatus(AuthStatus.SUCCESS);
  1011. user.setAuthId(identityAuth.getId());
  1012. save(user);
  1013. }
  1014. }
  1015. }
  1016. } catch (AlipayApiException e) {
  1017. throw new RuntimeException(e);
  1018. }
  1019. });
  1020. }
  1021. public Map<String, Object> oasisInfo(Long userId) {
  1022. Map<String, Object> map = new HashMap<>();
  1023. User user = userRepo.findById(userId).orElseThrow(new BusinessException("未找到用户信息"));
  1024. map.put("nickName", user.getNickname());
  1025. List<Asset> assets = assetRepo.findAllByOwnerIdAndStatusAndOasisIdNotNull(userId, AssetStatus.NORMAL);
  1026. List<OasisLoginDTO> oasisLoginDTOS = new ArrayList<>();
  1027. assets.forEach(asset -> {
  1028. OasisLoginDTO oasisLoginDTO = new OasisLoginDTO();
  1029. oasisLoginDTO.setOasisId(asset.getOasisId());
  1030. oasisLoginDTO.setAssetId(asset.getId());
  1031. oasisLoginDTO.setSource(asset.getStatus().getDescription());
  1032. Collection collection = collectionRepo.findFirstByOnShelfAndAssetId(true, asset.getId());
  1033. if (collection != null) {
  1034. oasisLoginDTO.setUrl(generalProperties.getHost() + "/9th/productDetail/" + collection
  1035. .getId() + "?id=" + collection.getId());
  1036. } else {
  1037. oasisLoginDTO.setUrl("未公开展示");
  1038. }
  1039. Showroom showroom = showroomRepo.findByOasisId(oasisLoginDTO.getOasisId())
  1040. .orElseThrow(new BusinessException("无记录 "));
  1041. List<ShowCollection> origin = showCollectionRepo.findAllByShowroomIdOrderBySort(showroom.getId());
  1042. List<ShowCollection> neo = new ArrayList<>();
  1043. if (origin != null) {
  1044. origin.forEach(orig -> collectionRepo.findById(orig.getCollectionId())
  1045. .ifPresent(collection1 -> {
  1046. orig.setStatus(showroomService.getStatus(collection1));
  1047. orig.setPrice(collection1.getPrice());
  1048. neo.add(orig);
  1049. }));
  1050. }
  1051. showroom.setCollections(neo);
  1052. User showRoomUser = SecurityUtils.getAuthenticatedUser();
  1053. if (showRoomUser != null && !showRoomUser.isAdmin()) {
  1054. List<NewsLike> likes = newsLikeRepo.findByUserIdAndShowroomId(showRoomUser
  1055. .getId(), showroom.getId());
  1056. showroom.setLiked(CollUtil.isNotEmpty(likes));
  1057. }
  1058. oasisLoginDTO.setShowroom(showroom);
  1059. oasisLoginDTOS.add(oasisLoginDTO);
  1060. });
  1061. map.put("oasisInfo", oasisLoginDTOS);
  1062. map.put("avatar", SecurityUtils.getAuthenticatedUser().getAvatar());
  1063. return map;
  1064. }
  1065. /**
  1066. * 流拍5次直接删号处罚
  1067. */
  1068. @Scheduled(cron = "0 0/10 * * * ?")
  1069. public void delUser() {
  1070. List<Long> userIds = auctionPassRecordRepo.checkUserId();
  1071. if (CollUtil.isNotEmpty(userIds)) {
  1072. log.info("流拍处罚:{}", userIds);
  1073. userRepo.softDeleteIn(userIds);
  1074. //清缓存
  1075. userIds.forEach(id -> {
  1076. cacheService.clearUserMy(id);
  1077. cacheService.clearUser(id);
  1078. });
  1079. }
  1080. }
  1081. public void savePoint(User user) {
  1082. //给积分
  1083. Long invitor = user.getCollectionInvitor();
  1084. if (ObjectUtils.isEmpty(user.getCollectionId()) || ObjectUtils.isEmpty(invitor)) {
  1085. this.noCollectionId(user);
  1086. return;
  1087. }
  1088. if (8573130L != user.getCollectionId()) return;
  1089. Collection collection = collectionRepo.findById(user.getCollectionId()).orElse(null);
  1090. if (collection == null) {
  1091. return;
  1092. }
  1093. if (user.getVipPoint() < 1) {
  1094. //有效新用户1个限购
  1095. user.setVipPoint(100);
  1096. userRepo.save(user);
  1097. cacheService.clearUserMy(user.getId());
  1098. cacheService.clearUser(user.getId());
  1099. }
  1100. //指标数量
  1101. int assignment = collection.getAssignment();
  1102. if (assignment < 1) {
  1103. return;
  1104. }
  1105. int inviteNum = userRepo.countAllByCollectionIdAndCollectionInvitorAndSettleAccountIdIsNotNull(
  1106. user.getCollectionId(), invitor);
  1107. int point = inviteNum / assignment;
  1108. log.info("邀请数量,{}-{}", invitor, inviteNum);
  1109. if (point < 1) {
  1110. return;
  1111. }
  1112. User parent = userRepo.findById(invitor).orElse(null);
  1113. if (parent == null) {
  1114. return;
  1115. }
  1116. if (parent.getVipPoint() < 1) {
  1117. //老用户可有一个限购
  1118. parent.setVipPoint(100);
  1119. userRepo.save(parent);
  1120. cacheService.clearUserMy(user.getId());
  1121. cacheService.clearUser(user.getId());
  1122. }
  1123. log.info("修改限购{}", invitor);
  1124. UserProperty userProperty = userPropertyRepo.findById(invitor).orElse(new UserProperty(invitor, 0));
  1125. if (userProperty.getMaxCount() < 10) {
  1126. if (parent.getVipPurchase() > 0 || parent.getCreatedAt().isAfter(LocalDateTime.of(2022, 7, 5, 0, 0, 0))) {
  1127. if (userProperty.getMaxCount() != point + 1) {
  1128. userProperty.setMaxCount(Math.min(point + 1, 10));
  1129. userPropertyRepo.save(userProperty);
  1130. log.info("邀请绑卡限购+1,{}", invitor);
  1131. return;
  1132. }
  1133. }
  1134. userProperty.setMaxCount(Math.min(point, 10));
  1135. userPropertyRepo.save(userProperty);
  1136. log.info("邀请绑卡限购+1,{}", invitor);
  1137. }
  1138. }
  1139. public void noCollectionId(User user) {
  1140. if (user.getCreatedAt().isBefore(LocalDateTime.of(2022, 7, 5, 0, 0, 0))) {
  1141. return;
  1142. }
  1143. if (user.getVipPoint() < 1) {
  1144. //有效新用户1个限购
  1145. user.setVipPoint(100);
  1146. userRepo.save(user);
  1147. cacheService.clearUserMy(user.getId());
  1148. cacheService.clearUser(user.getId());
  1149. }
  1150. }
  1151. }