diff --git a/drone-black-box/main.go b/drone-black-box/main.go index db5c146..d3f063d 100644 --- a/drone-black-box/main.go +++ b/drone-black-box/main.go @@ -26,6 +26,36 @@ type Server struct { db *sql.DB } +var allowedOrigins = map[string]struct{}{ + "http://localhost:4173": {}, + "http://127.0.0.1:4173": {}, + "http://localhost:5173": {}, + "http://127.0.0.1:5173": {}, +} + +// corsMiddleware adds the headers needed for cross-origin requests from the frontend. +func corsMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + origin := r.Header.Get("Origin") + if _, ok := allowedOrigins[origin]; ok { + w.Header().Set("Access-Control-Allow-Origin", origin) + w.Header().Set("Vary", "Origin") + } + + w.Header().Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Access-Control-Max-Age", "86400") + + // Handle preflight without hitting the underlying handlers. + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + + next.ServeHTTP(w, r) + }) +} + // Ingest handler func (s *Server) ingestHandler(w http.ResponseWriter, r *http.Request) { var event DroneEvent @@ -163,7 +193,7 @@ func main() { httpServer := &http.Server{ Addr: ":" + port, - Handler: mux, + Handler: corsMiddleware(mux), } // Graceful shutdown diff --git a/ilp-rest-service/src/main/java/io/github/js0ny/ilp_coursework/config/CorsConfig.java b/ilp-rest-service/src/main/java/io/github/js0ny/ilp_coursework/config/CorsConfig.java new file mode 100644 index 0000000..d8511e5 --- /dev/null +++ b/ilp-rest-service/src/main/java/io/github/js0ny/ilp_coursework/config/CorsConfig.java @@ -0,0 +1,27 @@ +package io.github.js0ny.ilp_coursework.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * Global CORS configuration so the frontend running on a different port can call the REST API. + */ +@Configuration +public class CorsConfig implements WebMvcConfigurer { + + private static final String[] ALLOWED_ORIGINS = new String[] { + "http://localhost:4173", + "http://127.0.0.1:4173", + "http://localhost:5173", + "http://127.0.0.1:5173" + }; + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins(ALLOWED_ORIGINS) + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH") + .allowedHeaders("*"); + } +}