| 1 | package edu.ucsb.cs156.frontiers.config; | |
| 2 | ||
| 3 | import com.fasterxml.jackson.databind.ObjectMapper; | |
| 4 | import edu.ucsb.cs156.frontiers.services.ApiKeyService; | |
| 5 | import jakarta.servlet.FilterChain; | |
| 6 | import jakarta.servlet.ServletException; | |
| 7 | import jakarta.servlet.http.HttpServletRequest; | |
| 8 | import jakarta.servlet.http.HttpServletResponse; | |
| 9 | import java.io.IOException; | |
| 10 | import java.util.Map; | |
| 11 | import lombok.extern.slf4j.Slf4j; | |
| 12 | import org.springframework.security.access.AccessDeniedException; | |
| 13 | import org.springframework.security.core.context.SecurityContext; | |
| 14 | import org.springframework.security.core.context.SecurityContextHolder; | |
| 15 | import org.springframework.web.filter.OncePerRequestFilter; | |
| 16 | ||
| 17 | @Slf4j | |
| 18 | public class ApiKeyFilter extends OncePerRequestFilter { | |
| 19 | ||
| 20 | ApiKeyService apiKeyService; | |
| 21 | ObjectMapper mapper; | |
| 22 | ||
| 23 | public ApiKeyFilter(ApiKeyService apiKeyService, ObjectMapper mapper) { | |
| 24 | this.apiKeyService = apiKeyService; | |
| 25 | this.mapper = mapper; | |
| 26 | } | |
| 27 | ||
| 28 | @Override | |
| 29 | protected void doFilterInternal( | |
| 30 | HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) | |
| 31 | throws ServletException, IOException { | |
| 32 | String apiKey = request.getHeader("X-API-KEY"); | |
| 33 |
2
1. doFilterInternal : negated conditional → KILLED 2. doFilterInternal : negated conditional → KILLED |
if (apiKey == null || apiKey.isEmpty()) { |
| 34 |
1
1. doFilterInternal : removed call to jakarta/servlet/FilterChain::doFilter → KILLED |
filterChain.doFilter(request, response); |
| 35 | return; | |
| 36 | } | |
| 37 | try { | |
| 38 | ApiKeyToken token = apiKeyService.authenticateKey(apiKey); | |
| 39 | SecurityContext context = SecurityContextHolder.createEmptyContext(); | |
| 40 |
1
1. doFilterInternal : removed call to org/springframework/security/core/context/SecurityContext::setAuthentication → KILLED |
context.setAuthentication(token); |
| 41 | SecurityContextHolder.setContext(context); | |
| 42 |
1
1. doFilterInternal : removed call to jakarta/servlet/FilterChain::doFilter → KILLED |
filterChain.doFilter(request, response); |
| 43 | } catch (AccessDeniedException e) { | |
| 44 | Map<String, String> responseMessage = Map.of("message", e.getMessage()); | |
| 45 |
1
1. doFilterInternal : removed call to jakarta/servlet/http/HttpServletResponse::setStatus → KILLED |
response.setStatus(HttpServletResponse.SC_FORBIDDEN); |
| 46 |
1
1. doFilterInternal : removed call to java/io/PrintWriter::write → KILLED |
response.getWriter().write(mapper.writeValueAsString(responseMessage)); |
| 47 | } | |
| 48 | } | |
| 49 | } | |
Mutations | ||
| 33 |
1.1 2.2 |
|
| 34 |
1.1 |
|
| 40 |
1.1 |
|
| 42 |
1.1 |
|
| 45 |
1.1 |
|
| 46 |
1.1 |