UserService.java 54 KB

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