提交 | 用户 | 时间
|
a6316e
|
1 |
package com.billion.common.config.serializer; |
A |
2 |
|
|
3 |
import java.io.IOException; |
|
4 |
import java.util.Objects; |
|
5 |
import com.fasterxml.jackson.core.JsonGenerator; |
|
6 |
import com.fasterxml.jackson.databind.BeanProperty; |
|
7 |
import com.fasterxml.jackson.databind.JsonMappingException; |
|
8 |
import com.fasterxml.jackson.databind.JsonSerializer; |
|
9 |
import com.fasterxml.jackson.databind.SerializerProvider; |
|
10 |
import com.fasterxml.jackson.databind.ser.ContextualSerializer; |
|
11 |
import com.billion.common.annotation.Sensitive; |
|
12 |
import com.billion.common.core.domain.model.LoginUser; |
|
13 |
import com.billion.common.enums.DesensitizedType; |
|
14 |
import com.billion.common.utils.SecurityUtils; |
|
15 |
|
|
16 |
/** |
|
17 |
* 数据脱敏序列化过滤 |
|
18 |
* |
|
19 |
* @author ruoyi |
|
20 |
*/ |
|
21 |
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer |
|
22 |
{ |
|
23 |
private DesensitizedType desensitizedType; |
|
24 |
|
|
25 |
@Override |
|
26 |
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException |
|
27 |
{ |
|
28 |
if (desensitization()) |
|
29 |
{ |
|
30 |
gen.writeString(desensitizedType.desensitizer().apply(value)); |
|
31 |
} |
|
32 |
else |
|
33 |
{ |
|
34 |
gen.writeString(value); |
|
35 |
} |
|
36 |
} |
|
37 |
|
|
38 |
@Override |
|
39 |
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) |
|
40 |
throws JsonMappingException |
|
41 |
{ |
|
42 |
Sensitive annotation = property.getAnnotation(Sensitive.class); |
|
43 |
if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) |
|
44 |
{ |
|
45 |
this.desensitizedType = annotation.desensitizedType(); |
|
46 |
return this; |
|
47 |
} |
|
48 |
return prov.findValueSerializer(property.getType(), property); |
|
49 |
} |
|
50 |
|
|
51 |
/** |
|
52 |
* 是否需要脱敏处理 |
|
53 |
*/ |
|
54 |
private boolean desensitization() |
|
55 |
{ |
|
56 |
try |
|
57 |
{ |
|
58 |
LoginUser securityUser = SecurityUtils.getLoginUser(); |
|
59 |
// 管理员不脱敏 |
|
60 |
return !securityUser.getUser().isAdmin(); |
|
61 |
} |
|
62 |
catch (Exception e) |
|
63 |
{ |
|
64 |
return true; |
|
65 |
} |
|
66 |
} |
|
67 |
} |