Skip to content

Commit

Permalink
Merge pull request #177 from Media-XI/develop
Browse files Browse the repository at this point in the history
feat: sentry set user real address from x-forward header
  • Loading branch information
Hoon9901 authored Aug 1, 2024
2 parents 98890c8 + f98a458 commit 409cb95
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/main/java/com/example/codebase/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.codebase.config;

import com.example.codebase.filter.MDCLoggingFilter;
import com.example.codebase.filter.SentryInterceptor;
import com.example.codebase.filter.ServletLoggingFilter;
import com.example.codebase.filter.security.RefererCheckIntercepter;
import com.example.codebase.util.HTMLCharacterEscapes;
Expand Down Expand Up @@ -46,6 +47,7 @@ public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RefererCheckIntercepter(environment))
.addPathPatterns("/api/**");
registry.addInterceptor(new SentryInterceptor());
}

@Bean
Expand Down
31 changes: 31 additions & 0 deletions src/main/java/com/example/codebase/filter/SentryInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.example.codebase.filter;

import io.sentry.Sentry;
import io.sentry.protocol.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class SentryInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String ipAddress = getClientIpAddress(request);
User realIpUser = new User();
realIpUser.setIpAddress(ipAddress);
if (ipAddress != null) {
Sentry.configureScope(scope -> {
scope.setUser(realIpUser);
});
}
return true;
}

private String getClientIpAddress(HttpServletRequest request) {
String xForwardedForHeader = request.getHeader("X-Forwarded-For");
if (xForwardedForHeader != null) {
return xForwardedForHeader.split(",")[0];
}
return request.getRemoteAddr();
}
}

0 comments on commit 409cb95

Please sign in to comment.