UserService.java 48 KB

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