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();
|
}
|
}
|