package com.zy.acs.manager.common.interceptor; import com.zy.acs.manager.common.annotation.IntegrationAuth; import com.zy.acs.manager.core.domain.type.NamespaceType; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Intercepts open API calls so they can be audited via IntegrationRecordAdvice. */ @Slf4j @Component public class IntegrationOpenApiInterceptor implements HandlerInterceptor { private static final String ATTR_CONTEXT = IntegrationOpenApiInterceptor.class.getName() + ".CONTEXT"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { if (!(handler instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) handler; IntegrationAuth integrationAuth = findIntegrationAuth(handlerMethod); if (integrationAuth == null || integrationAuth.value() == IntegrationAuth.Enable.SKIP_LOG) { return true; } NamespaceType namespaceType = integrationAuth.name() == null ? NamespaceType.NONE : integrationAuth.name(); IntegrationRequestContext context = new IntegrationRequestContext( namespaceType, handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName(), System.currentTimeMillis() ); request.setAttribute(ATTR_CONTEXT, context); return true; } public static IntegrationRequestContext getContext(HttpServletRequest request) { Object attribute = request.getAttribute(ATTR_CONTEXT); if (attribute instanceof IntegrationRequestContext) { return (IntegrationRequestContext) attribute; } return null; } private IntegrationAuth findIntegrationAuth(HandlerMethod handlerMethod) { IntegrationAuth annotation = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getMethod(), IntegrationAuth.class); if (annotation != null) { return annotation; } return AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), IntegrationAuth.class); } @Getter public static class IntegrationRequestContext { private IntegrationRequestContext(NamespaceType namespaceType, String handler, long startAt) { this.namespaceType = namespaceType; this.handler = handler; this.startAt = startAt; } private final NamespaceType namespaceType; private final String handler; private final long startAt; } }