IdentityAuthService.java 14 KB

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