2021-12-23 23:07:54 +08:00
|
|
|
package com.ruoyi.common.jackson;
|
|
|
|
|
|
|
|
import com.fasterxml.jackson.core.JsonGenerator;
|
|
|
|
import com.fasterxml.jackson.databind.BeanProperty;
|
|
|
|
import com.fasterxml.jackson.databind.JsonMappingException;
|
|
|
|
import com.fasterxml.jackson.databind.JsonSerializer;
|
|
|
|
import com.fasterxml.jackson.databind.SerializerProvider;
|
|
|
|
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
|
|
|
|
import com.ruoyi.common.annotation.Sensitive;
|
2021-12-28 11:51:01 +08:00
|
|
|
import com.ruoyi.common.core.service.SensitiveService;
|
2021-12-23 23:07:54 +08:00
|
|
|
import com.ruoyi.common.enums.SensitiveStrategy;
|
2021-12-28 11:51:01 +08:00
|
|
|
import com.ruoyi.common.utils.spring.SpringUtils;
|
2021-12-23 23:07:54 +08:00
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.util.Objects;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 数据脱敏json序列化工具
|
|
|
|
* @author Yjoioooo
|
|
|
|
*/
|
|
|
|
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
|
|
|
|
|
|
|
|
private SensitiveStrategy strategy;
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
|
2021-12-28 11:51:01 +08:00
|
|
|
SensitiveService sensitiveService = SpringUtils.getBean(SensitiveService.class);
|
|
|
|
if (sensitiveService.isSensitive()){
|
2021-12-23 23:07:54 +08:00
|
|
|
gen.writeString(value);
|
|
|
|
} else {
|
|
|
|
gen.writeString(strategy.desensitizer().apply(value));
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
|
|
|
|
Sensitive annotation = property.getAnnotation(Sensitive.class);
|
|
|
|
if (Objects.nonNull(annotation)&&Objects.equals(String.class, property.getType().getRawClass())) {
|
|
|
|
this.strategy = annotation.strategy();
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
return prov.findValueSerializer(property.getType(), property);
|
|
|
|
}
|
|
|
|
}
|