UserService.java 53 KB

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