package middleware import ( "authentication/helper" "net/http" "os" "strings" ) const defaultFrontendOrigin = "http://localhost:5173" func allowedFrontendOrigins() map[string]struct{} { raw := os.Getenv("FRONTEND_ORIGINS") if strings.TrimSpace(raw) == "" { raw = defaultFrontendOrigin } allowed := make(map[string]struct{}) for _, origin := range strings.Split(raw, ",") { trimmed := strings.TrimSpace(origin) if trimmed != "" { allowed[trimmed] = struct{}{} } } return allowed } func FrontendOriginWhitelist(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := strings.TrimSpace(r.Header.Get("Origin")) if origin == "" { helper.RespondWithError(w, http.StatusBadRequest, "missing origin header") return } if _, ok := allowedFrontendOrigins()[origin]; !ok { helper.RespondWithError(w, http.StatusForbidden, "forbidden origin") return } next.ServeHTTP(w, r) }) }