|
| 1 | +package lavalink.server.config; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | +import org.springframework.context.annotation.Configuration; |
| 6 | +import org.springframework.http.HttpStatus; |
| 7 | +import org.springframework.web.servlet.HandlerInterceptor; |
| 8 | +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; |
| 9 | +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; |
| 10 | + |
| 11 | +import javax.servlet.http.HttpServletRequest; |
| 12 | +import javax.servlet.http.HttpServletResponse; |
| 13 | + |
| 14 | +@Configuration |
| 15 | +public class RequestAuthorizationFilter implements HandlerInterceptor, WebMvcConfigurer { |
| 16 | + |
| 17 | + private static final Logger log = LoggerFactory.getLogger(RequestAuthorizationFilter.class); |
| 18 | + private ServerConfig serverConfig; |
| 19 | + private MetricsPrometheusConfigProperties metricsConfig; |
| 20 | + |
| 21 | + public RequestAuthorizationFilter(ServerConfig serverConfig, MetricsPrometheusConfigProperties metricsConfig) { |
| 22 | + this.serverConfig = serverConfig; |
| 23 | + this.metricsConfig = metricsConfig; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { |
| 28 | + // Collecting metrics is anonymous |
| 29 | + if (!metricsConfig.getEndpoint().isEmpty() |
| 30 | + && request.getServletPath().equals(metricsConfig.getEndpoint())) return true; |
| 31 | + |
| 32 | + if (request.getServletPath().equals("/error")) return true; |
| 33 | + |
| 34 | + String authorization = request.getHeader("Authorization"); |
| 35 | + |
| 36 | + if (authorization == null || !authorization.equals(serverConfig.getPassword())) { |
| 37 | + String method = request.getMethod(); |
| 38 | + String path = request.getRequestURI().substring(request.getContextPath().length()); |
| 39 | + String ip = request.getRemoteAddr(); |
| 40 | + |
| 41 | + if (authorization == null) { |
| 42 | + log.warn("Authorization missing for {} on {} {}", ip, method, path); |
| 43 | + response.setStatus(HttpStatus.UNAUTHORIZED.value()); |
| 44 | + return false; |
| 45 | + } |
| 46 | + log.warn("Authorization failed for {} on {} {}", ip, method, path); |
| 47 | + response.setStatus(HttpStatus.FORBIDDEN.value()); |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public void addInterceptors(InterceptorRegistry registry) { |
| 56 | + registry.addInterceptor(this); |
| 57 | + } |
| 58 | +} |
0 commit comments