Files
hlaskovnik-reimagined/backend/middleware.go
T

64 lines
1.5 KiB
Go

package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"time"
"crypto/subtle"
)
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
expectedKey := os.Getenv("FRONTEND_API_KEY")
if expectedKey == "" {
http.Error(w, "server misconfigured", 500)
return
}
authHeader := r.Header.Get("Authorization")
expectedHeader := "Bearer " + expectedKey
if subtle.ConstantTimeCompare([]byte(authHeader), []byte(expectedHeader)) != 1 {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func logMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqMethod := r.Method
reqUrl := r.URL.String()
reqIp := r.RemoteAddr
reqHeaderContentType := r.Header.Get("Content-Type")
defer r.Body.Close()
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "[log] Failed to read body", http.StatusBadRequest)
return
}
fmt.Printf("\n[%s] %s request on %s\n", reqIp, reqMethod, reqUrl)
fmt.Println("Timestamp (UTC): " + time.Now().UTC().String())
fmt.Println("Header Content-Type: " + reqHeaderContentType)
if len(bodyBytes) == 0 {
fmt.Println("Body: <empty>")
} else {
fmt.Println("Body: " + string(bodyBytes))
}
// restore the request body for later
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
next.ServeHTTP(w, r)
})
}