8921fd1467
- Remove secrets from Git (.env) - Remove debug token endpoint - Fix login to reject unauthorized access in production - Remove HS256 fallback in JWT validation (RS256 only) - Fix SQL injection in journal.go countQuery - Fix CORS to use explicit origins only (no wildcard) - Add security headers middleware (CSP, HSTS, etc.) - Add input validation helpers - Build successful
70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/rs/zerolog"
|
|
)
|
|
|
|
// CORS middleware med strikt origin-kontroll
|
|
func CORS(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
origin := r.Header.Get("Origin")
|
|
|
|
// Hämta tillåtna origins från miljövariabel
|
|
allowedOrigins := os.Getenv("CORS_ORIGINS")
|
|
if allowedOrigins == "" {
|
|
allowedOrigins = "http://localhost:3000"
|
|
}
|
|
|
|
origins := strings.Split(allowedOrigins, ",")
|
|
allowed := false
|
|
|
|
for _, o := range origins {
|
|
o = strings.TrimSpace(o)
|
|
if o == origin {
|
|
allowed = true
|
|
break
|
|
}
|
|
}
|
|
|
|
// I utveckling, tillåt localhost
|
|
if !allowed && strings.HasPrefix(origin, "http://localhost:") {
|
|
allowed = true
|
|
}
|
|
|
|
if allowed {
|
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
}
|
|
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Request-ID")
|
|
w.Header().Set("Access-Control-Max-Age", "86400")
|
|
|
|
if r.Method == "OPTIONS" {
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func Logger(logger zerolog.Logger) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
next.ServeHTTP(w, r)
|
|
logger.Info().
|
|
Str("method", r.Method).
|
|
Str("path", r.URL.Path).
|
|
Dur("duration", time.Since(start)).
|
|
Msg("request")
|
|
})
|
|
}
|
|
}
|