刘光辉
昨天 bb638871a7fb692d80f1b7a758f991dc0879002c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package jnpf.audit.sdk;
 
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;
 
/** Restricts SDK audit events to configured application request sources. */
public class AuditRequestScopeFilter {
 
    private static final String HEADER_APP_CODE = "App-Code";
    private static final String HEADER_APP_SCOPE = "Jnpf-App-Scope";
 
    private final boolean frontendOnly;
    private final Set<String> allowedAppCodes;
 
    public AuditRequestScopeFilter(boolean frontendOnly, String allowedAppCodes) {
        this.frontendOnly = frontendOnly;
        Set<String> normalized = new LinkedHashSet<>();
        if (allowedAppCodes != null) {
            for (String code : allowedAppCodes.split(",")) {
                if (code != null && !code.trim().isEmpty()) {
                    normalized.add(code.trim().toUpperCase(Locale.ROOT));
                }
            }
        }
        this.allowedAppCodes = normalized.isEmpty()
                ? Collections.emptySet() : Collections.unmodifiableSet(normalized);
    }
 
    public boolean acceptsCurrentRequest() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (!(attributes instanceof ServletRequestAttributes)) {
            return accepts(null, null);
        }
        ServletRequestAttributes servletAttributes = (ServletRequestAttributes) attributes;
        return accepts(servletAttributes.getRequest().getHeader(HEADER_APP_SCOPE),
                servletAttributes.getRequest().getHeader(HEADER_APP_CODE));
    }
 
    public boolean accepts(String appScope, String appCode) {
        if (frontendOnly && !"FRONTEND".equalsIgnoreCase(trim(appScope))) {
            return false;
        }
        return allowedAppCodes.isEmpty()
                || allowedAppCodes.contains(trim(appCode).toUpperCase(Locale.ROOT));
    }
 
    private static String trim(String value) {
        return value == null ? "" : value.trim();
    }
}