UserService.java 59 KB

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