IdentityAuthService.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. identityAuthRepo.deleteDuplicated(identityAuth.getUserId(), identityAuth.getId());
  61. }
  62. public void audit(Long id, AuthStatus status, String reason) {
  63. IdentityAuth auth = identityAuthRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("申请不存在"));
  64. if (auth.getStatus() != AuthStatus.PENDING) {
  65. throw new BusinessException("已经审核过");
  66. }
  67. User user = userRepo.findByIdAndDelFalse(auth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  68. if (user.getAuthStatus() != AuthStatus.SUCCESS) {
  69. if (status == AuthStatus.SUCCESS) {
  70. user.setAuthId(auth.getId());
  71. }
  72. user.setAuthStatus(status);
  73. userRepo.save(user);
  74. }
  75. auth.setStatus(status);
  76. auth.setReason(reason);
  77. auth.setAutoValidated(true);
  78. identityAuthRepo.save(auth);
  79. identityAuthRepo.deleteDuplicated(auth.getUserId(), auth.getId());
  80. }
  81. public List<User> repeat(String idNo, Long userId) {
  82. List<IdentityAuth> auths = identityAuthRepo.findAllByIdNoAndUserIdIsNotAndDelFalse(idNo, userId);
  83. if (auths.isEmpty()) {
  84. return null;
  85. }
  86. List<Long> userIds = auths.stream().map(IdentityAuth::getUserId).distinct().collect(Collectors.toList());
  87. return userRepo.findByIdInAndDelFalse(userIds);
  88. }
  89. // public void validate(String name, String phone, String idno) {
  90. // String body = HttpRequest.post("https://jubrige.market.alicloudapi.com/mobile/3-validate-transfer")
  91. // .header("Authorization", "APPCODE b48bc8f6759345a79ae20a951f03dabe")
  92. // .contentType(HttpRequest.CONTENT_TYPE_FORM)
  93. // .form("idCardNo", idno)
  94. // .form("mobile", phone)
  95. // .form("name", name)
  96. // .body();
  97. // JSONObject jsonObject = JSONObject.parseObject(body);
  98. // if (jsonObject.getInteger("code") != 200) {
  99. // String msg = jsonObject.getString("msg");
  100. // throw new BusinessException(msg);
  101. // } else {
  102. // JSONObject data = jsonObject.getJSONObject("data");
  103. // int result = data.getIntValue("result");
  104. // String desc = data.getString("desc");
  105. // if (result != 0) {
  106. // throw new BusinessException(desc);
  107. // } else {
  108. // log.info("{} {} {} 实名认证通过", name, phone, idno);
  109. // }
  110. // }
  111. // }
  112. public void validate(String name, String phone, String idno) {
  113. String body = HttpRequest.post("https://zid.market.alicloudapi.com/idcheck/Post")
  114. .header("Authorization", "APPCODE b48bc8f6759345a79ae20a951f03dabe")
  115. .contentType(HttpRequest.CONTENT_TYPE_FORM)
  116. .form("cardNo", idno)
  117. .form("realName", name)
  118. .body();
  119. JSONObject jsonObject = JSONObject.parseObject(body);
  120. if (jsonObject.getInteger("error_code") != 0) {
  121. String msg = jsonObject.getString("reason");
  122. throw new BusinessException(msg);
  123. } else {
  124. JSONObject data = jsonObject.getJSONObject("result");
  125. boolean isOK = Optional.ofNullable(data.getBoolean("isok")).orElse(Boolean.FALSE);
  126. if (!isOK) {
  127. throw new BusinessException("不匹配");
  128. } else {
  129. log.info("{} {} {} 实名认证通过", name, phone, idno);
  130. }
  131. }
  132. }
  133. public void removeDuplicated() {
  134. boolean hasMore = true;
  135. int pageNum = 0;
  136. AtomicInteger count = new AtomicInteger();
  137. while (hasMore) {
  138. Page<Long> page = identityAuthRepo.listUserId(PageRequest.of(pageNum, 100));
  139. List<Long> userIds = page.getContent();
  140. userIds.parallelStream().forEach(userId -> {
  141. userRepo.findById(userId).ifPresent(user -> {
  142. log.info("removeDuplicated {}/{} ", count.incrementAndGet(), page.getTotalElements());
  143. List<IdentityAuth> list = identityAuthRepo.findByUserId(userId);
  144. if (list.size() > 1) {
  145. IdentityAuth auth = list.stream()
  146. .filter(i -> i.getStatus() == AuthStatus.SUCCESS)
  147. .findAny().orElse(null);
  148. if (auth != null) {
  149. userRepo.setAuthStatus(user.getId(), auth.getStatus(), auth.getId());
  150. int num = identityAuthRepo.deleteDuplicated(user.getId(), auth.getId());
  151. log.info("deleted {}", num);
  152. return;
  153. }
  154. auth = list.stream()
  155. .filter(i -> i.getStatus() == AuthStatus.PENDING)
  156. .findAny().orElse(null);
  157. if (auth != null) {
  158. userRepo.setAuthStatus(user.getId(), auth.getStatus(), auth.getId());
  159. int num = identityAuthRepo.deleteDuplicated(user.getId(), auth.getId());
  160. log.info("deleted {}", num);
  161. return;
  162. }
  163. auth = list.stream()
  164. .filter(i -> i.getStatus() == AuthStatus.FAIL)
  165. .findAny().orElse(null);
  166. if (auth != null) {
  167. userRepo.setAuthStatus(user.getId(), auth.getStatus(), auth.getId());
  168. int num = identityAuthRepo.deleteDuplicated(user.getId(), auth.getId());
  169. log.info("deleted {}", num);
  170. return;
  171. }
  172. } else if (list.size() == 1) {
  173. userRepo.setAuthStatus(user.getId(), list.get(0).getStatus(), list.get(0).getId());
  174. }
  175. });
  176. });
  177. hasMore = page.hasNext();
  178. pageNum++;
  179. }
  180. }
  181. @Scheduled(fixedRate = 60000)
  182. @RedisLock(value = "autoValidate", expire = 30, unit = TimeUnit.MINUTES)
  183. public void autoValidate() {
  184. if (!sysConfigService.getBoolean("auto_validate")) return;
  185. log.info("autoValidate");
  186. if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
  187. return;
  188. }
  189. try {
  190. List<IdentityAuth> list = identityAuthRepo.findByStatusAndAutoValidated(AuthStatus.PENDING, false);
  191. list.parallelStream().forEach(identityAuth -> {
  192. log.info("实名 {}", identityAuth.getRealName());
  193. boolean success = false;
  194. String reason = null;
  195. User user = userRepo.findById(identityAuth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
  196. if (user.getAuthStatus() == AuthStatus.SUCCESS) {
  197. audit(identityAuth.getId(), AuthStatus.SUCCESS, null);
  198. return;
  199. }
  200. 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()
  201. .toLowerCase())) {
  202. audit(identityAuth.getId(), AuthStatus.FAIL, "身份证格式错误");
  203. return;
  204. } else {
  205. LocalDate birth = DateTimeUtils.toLocalDate(identityAuth.getIdNo().substring(6, 14), "yyyyMMdd");
  206. long age = ChronoUnit.YEARS.between(birth, LocalDate.now());
  207. if (age < 18) {
  208. audit(identityAuth.getId(), AuthStatus.FAIL, "未满18岁");
  209. return;
  210. } else if (age > 60) {
  211. audit(identityAuth.getId(), AuthStatus.FAIL, "超过60岁");
  212. return;
  213. }
  214. }
  215. int count = identityAuthRepo.countByIdNoAndStatus(identityAuth.getIdNo(), AuthStatus.SUCCESS);
  216. if (count >= 3) {
  217. success = false;
  218. reason = "同一身份证注册超过3个";
  219. } else {
  220. try {
  221. validate(identityAuth.getRealName(), user.getPhone(), identityAuth.getIdNo());
  222. success = true;
  223. } catch (Exception e) {
  224. log.error("自动实名出错", e);
  225. reason = e.getMessage();
  226. }
  227. }
  228. audit(identityAuth.getId(), success ? AuthStatus.SUCCESS : AuthStatus.PENDING, reason);
  229. });
  230. } catch (Exception e) {
  231. log.error("批量自动实名出错", e);
  232. }
  233. }
  234. }