IdentityAuthService.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. package com.izouma.nineth.service;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.github.kevinsawicki.http.HttpRequest;
  4. import com.izouma.nineth.annotations.RedisLock;
  5. import com.izouma.nineth.domain.IdentityAuth;
  6. import com.izouma.nineth.domain.User;
  7. import com.izouma.nineth.dto.PageQuery;
  8. import com.izouma.nineth.enums.AuthStatus;
  9. import com.izouma.nineth.exception.BusinessException;
  10. import com.izouma.nineth.repo.IdentityAuthRepo;
  11. import com.izouma.nineth.repo.UserRepo;
  12. import com.izouma.nineth.utils.DateTimeUtils;
  13. import com.izouma.nineth.utils.JpaUtils;
  14. import lombok.AllArgsConstructor;
  15. import lombok.extern.slf4j.Slf4j;
  16. import org.springframework.core.env.Environment;
  17. import org.springframework.data.domain.Page;
  18. import org.springframework.data.domain.PageRequest;
  19. import org.springframework.data.redis.core.RedisTemplate;
  20. import org.springframework.scheduling.annotation.Scheduled;
  21. import org.springframework.stereotype.Service;
  22. import java.time.LocalDate;
  23. import java.time.temporal.ChronoUnit;
  24. import java.util.Arrays;
  25. import java.util.List;
  26. import java.util.Optional;
  27. import java.util.concurrent.TimeUnit;
  28. import java.util.concurrent.atomic.AtomicInteger;
  29. import java.util.regex.Pattern;
  30. import java.util.stream.Collectors;
  31. @Service
  32. @AllArgsConstructor
  33. @Slf4j
  34. public class IdentityAuthService {
  35. private IdentityAuthRepo identityAuthRepo;
  36. private UserRepo userRepo;
  37. private AdapayService adapayService;
  38. private RedisTemplate<String, Object> redisTemplate;
  39. private Environment env;
  40. private SysConfigService sysConfigService;
  41. public Page<IdentityAuth> all(PageQuery pageQuery) {
  42. return identityAuthRepo.findAll(JpaUtils.toSpecification(pageQuery, IdentityAuth.class), JpaUtils.toPageRequest(pageQuery));
  43. }
  44. public void apply(IdentityAuth identityAuth) {
  45. if (identityAuth.getUserId() == null) {
  46. throw new BusinessException("用户不存在");
  47. }
  48. User user = userRepo.findByIdAndDelFalse(identityAuth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  49. List<IdentityAuth> auths = identityAuthRepo.findByUserIdAndDelFalse(identityAuth.getUserId());
  50. auths.stream().filter(auth -> auth.getStatus() == AuthStatus.PENDING).findAny().ifPresent(a -> {
  51. throw new BusinessException("正在审核中,请勿重复提交");
  52. });
  53. auths.stream().filter(auth -> auth.getStatus() == AuthStatus.SUCCESS).findAny().ifPresent(a -> {
  54. throw new BusinessException("已认证,请勿重复提交");
  55. });
  56. identityAuth.setStatus(AuthStatus.PENDING);
  57. identityAuthRepo.save(identityAuth);
  58. user.setAuthStatus(AuthStatus.PENDING);
  59. userRepo.save(user);
  60. }
  61. public void audit(Long id, AuthStatus status, String reason) {
  62. IdentityAuth auth = identityAuthRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("申请不存在"));
  63. if (auth.getStatus() != AuthStatus.PENDING) {
  64. throw new BusinessException("已经审核过");
  65. }
  66. User user = userRepo.findByIdAndDelFalse(auth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  67. if (user.getAuthStatus() != AuthStatus.SUCCESS) {
  68. if (status == AuthStatus.SUCCESS) {
  69. user.setAuthId(auth.getId());
  70. }
  71. user.setAuthStatus(status);
  72. userRepo.save(user);
  73. }
  74. auth.setStatus(status);
  75. auth.setReason(reason);
  76. auth.setAutoValidated(true);
  77. identityAuthRepo.save(auth);
  78. }
  79. public List<User> repeat(String idNo, Long userId) {
  80. List<IdentityAuth> auths = identityAuthRepo.findAllByIdNoAndUserIdIsNotAndDelFalse(idNo, userId);
  81. if (auths.isEmpty()) {
  82. return null;
  83. }
  84. List<Long> userIds = auths.stream().map(IdentityAuth::getUserId).distinct().collect(Collectors.toList());
  85. return userRepo.findByIdInAndDelFalse(userIds);
  86. }
  87. // public void validate(String name, String phone, String idno) {
  88. // String body = HttpRequest.post("https://jubrige.market.alicloudapi.com/mobile/3-validate-transfer")
  89. // .header("Authorization", "APPCODE b48bc8f6759345a79ae20a951f03dabe")
  90. // .contentType(HttpRequest.CONTENT_TYPE_FORM)
  91. // .form("idCardNo", idno)
  92. // .form("mobile", phone)
  93. // .form("name", name)
  94. // .body();
  95. // JSONObject jsonObject = JSONObject.parseObject(body);
  96. // if (jsonObject.getInteger("code") != 200) {
  97. // String msg = jsonObject.getString("msg");
  98. // throw new BusinessException(msg);
  99. // } else {
  100. // JSONObject data = jsonObject.getJSONObject("data");
  101. // int result = data.getIntValue("result");
  102. // String desc = data.getString("desc");
  103. // if (result != 0) {
  104. // throw new BusinessException(desc);
  105. // } else {
  106. // log.info("{} {} {} 实名认证通过", name, phone, idno);
  107. // }
  108. // }
  109. // }
  110. public void validate(String name, String phone, String idno) {
  111. String body = HttpRequest.post("https://zid.market.alicloudapi.com/idcheck/Post")
  112. .header("Authorization", "APPCODE b48bc8f6759345a79ae20a951f03dabe")
  113. .contentType(HttpRequest.CONTENT_TYPE_FORM)
  114. .form("cardNo", idno)
  115. .form("realName", name)
  116. .body();
  117. JSONObject jsonObject = JSONObject.parseObject(body);
  118. if (jsonObject.getInteger("error_code") != 0) {
  119. String msg = jsonObject.getString("reason");
  120. throw new BusinessException(msg);
  121. } else {
  122. JSONObject data = jsonObject.getJSONObject("result");
  123. boolean isOK = Optional.ofNullable(data.getBoolean("isok")).orElse(Boolean.FALSE);
  124. if (!isOK) {
  125. throw new BusinessException("不匹配");
  126. } else {
  127. log.info("{} {} {} 实名认证通过", name, phone, idno);
  128. }
  129. }
  130. }
  131. public void removeDuplicated() {
  132. boolean hasMore = true;
  133. int pageNum = 1;
  134. AtomicInteger count = new AtomicInteger();
  135. while (hasMore) {
  136. Page<Long> page = identityAuthRepo.listUserId(PageRequest.of(pageNum, 100));
  137. List<Long> userIds = page.getContent();
  138. userIds.parallelStream().forEach(userId -> {
  139. userRepo.findById(userId).ifPresent(user -> {
  140. log.info("removeDuplicated {}/{} ", count.incrementAndGet(), page.getTotalElements());
  141. List<IdentityAuth> list = identityAuthRepo.findByUserId(userId);
  142. if (list.size() > 1) {
  143. IdentityAuth auth = list.stream()
  144. .filter(i -> i.getStatus() == AuthStatus.SUCCESS)
  145. .findAny().orElse(null);
  146. if (auth != null) {
  147. userRepo.setAuthStatus(user.getId(), auth.getStatus(), auth.getId());
  148. identityAuthRepo.deleteDuplicated(user.getId(), auth.getId());
  149. return;
  150. }
  151. auth = list.stream()
  152. .filter(i -> i.getStatus() == AuthStatus.PENDING)
  153. .findAny().orElse(null);
  154. if (auth != null) {
  155. userRepo.setAuthStatus(user.getId(), auth.getStatus(), auth.getId());
  156. identityAuthRepo.deleteDuplicated(user.getId(), auth.getId());
  157. return;
  158. }
  159. auth = list.stream()
  160. .filter(i -> i.getStatus() == AuthStatus.FAIL)
  161. .findAny().orElse(null);
  162. if (auth != null) {
  163. userRepo.setAuthStatus(user.getId(), auth.getStatus(), auth.getId());
  164. identityAuthRepo.deleteDuplicated(user.getId(), auth.getId());
  165. return;
  166. }
  167. } else if (list.size() == 1) {
  168. userRepo.setAuthStatus(user.getId(), list.get(0).getStatus(), list.get(0).getId());
  169. }
  170. });
  171. });
  172. hasMore = page.hasNext();
  173. pageNum++;
  174. }
  175. }
  176. @Scheduled(fixedRate = 60000)
  177. @RedisLock(value = "autoValidate", expire = 30, unit = TimeUnit.MINUTES)
  178. public void autoValidate() {
  179. if (!sysConfigService.getBoolean("auto_validate")) return;
  180. log.info("autoValidate");
  181. if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
  182. return;
  183. }
  184. try {
  185. List<IdentityAuth> list = identityAuthRepo.findByStatusAndAutoValidated(AuthStatus.PENDING, false);
  186. list.parallelStream().forEach(identityAuth -> {
  187. boolean success = false;
  188. String reason = null;
  189. User user = userRepo.findById(identityAuth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  190. if (user.getAuthStatus() == AuthStatus.SUCCESS) {
  191. audit(identityAuth.getId(), AuthStatus.SUCCESS, null);
  192. return;
  193. }
  194. if (!Pattern.matches("[1-9]{1}[0-9]{5}(19|20)[0-9]{2}((0[1-9]{1})|(1[0-2]{1}))((0[1-9]{1})|([1-2]{1}[0-9]{1}|(3[0-1]{1})))[0-9]{3}[0-9x]{1}", identityAuth.getIdNo()
  195. .toLowerCase())) {
  196. audit(identityAuth.getId(), AuthStatus.FAIL, "身份证格式错误");
  197. return;
  198. } else {
  199. LocalDate birth = DateTimeUtils.toLocalDate(identityAuth.getIdNo().substring(6, 14), "yyyyMMdd");
  200. long age = ChronoUnit.YEARS.between(birth, LocalDate.now());
  201. if (age < 18) {
  202. audit(identityAuth.getId(), AuthStatus.FAIL, "未满18岁");
  203. return;
  204. } else if (age > 60) {
  205. audit(identityAuth.getId(), AuthStatus.FAIL, "超过60岁");
  206. return;
  207. }
  208. }
  209. int count = identityAuthRepo.countByIdNoAndStatus(identityAuth.getIdNo(), AuthStatus.SUCCESS);
  210. if (count >= 3) {
  211. success = false;
  212. reason = "同一身份证注册超过3个";
  213. } else {
  214. try {
  215. validate(identityAuth.getRealName(), user.getPhone(), identityAuth.getIdNo());
  216. success = true;
  217. } catch (Exception e) {
  218. reason = e.getMessage();
  219. }
  220. }
  221. audit(identityAuth.getId(), success ? AuthStatus.SUCCESS : AuthStatus.PENDING, reason);
  222. });
  223. } catch (Exception ignored) {
  224. }
  225. }
  226. }