You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
2.1 KiB

1 year ago
  1. package com.inscloudtech.common.jackson;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import com.fasterxml.jackson.core.JsonGenerator;
  4. import com.fasterxml.jackson.databind.BeanProperty;
  5. import com.fasterxml.jackson.databind.JsonMappingException;
  6. import com.fasterxml.jackson.databind.JsonSerializer;
  7. import com.fasterxml.jackson.databind.SerializerProvider;
  8. import com.fasterxml.jackson.databind.ser.ContextualSerializer;
  9. import com.inscloudtech.common.annotation.Sensitive;
  10. import com.inscloudtech.common.core.service.SensitiveService;
  11. import com.inscloudtech.common.enums.SensitiveStrategy;
  12. import com.inscloudtech.common.utils.spring.SpringUtils;
  13. import lombok.extern.slf4j.Slf4j;
  14. import org.springframework.beans.BeansException;
  15. import java.io.IOException;
  16. import java.util.Objects;
  17. /**
  18. * 数据脱敏json序列化工具
  19. *
  20. * @author Yjoioooo
  21. */
  22. @Slf4j
  23. public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
  24. private SensitiveStrategy strategy;
  25. @Override
  26. public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
  27. try {
  28. SensitiveService sensitiveService = SpringUtils.getBean(SensitiveService.class);
  29. if (ObjectUtil.isNotNull(sensitiveService) && sensitiveService.isSensitive()) {
  30. gen.writeString(strategy.desensitizer().apply(value));
  31. } else {
  32. gen.writeString(value);
  33. }
  34. } catch (BeansException e) {
  35. log.error("脱敏实现不存在, 采用默认处理 => {}", e.getMessage());
  36. gen.writeString(value);
  37. }
  38. }
  39. @Override
  40. public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
  41. Sensitive annotation = property.getAnnotation(Sensitive.class);
  42. if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) {
  43. this.strategy = annotation.strategy();
  44. return this;
  45. }
  46. return prov.findValueSerializer(property.getType(), property);
  47. }
  48. }