package middleware import ( "context" "marmic/servicetrade-toolbox/internal/api" "net/http" ) // Define a custom key type to avoid collisions type contextKey string // SessionKey is the key used to store session in request context const SessionKey = contextKey("session") var SessionStore = api.NewSessionStore() func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("PHPSESSID") if err != nil { http.Redirect(w, r, "/login", http.StatusSeeOther) return } sessionID := cookie.Value session, exists := SessionStore.Get(sessionID) if !exists { session = api.NewSession() session.Cookie = "PHPSESSID=" + sessionID if err := session.ValidateSession(); err != nil { http.Redirect(w, r, "/login", http.StatusSeeOther) return } SessionStore.Set(sessionID, session) } ctx := context.WithValue(r.Context(), SessionKey, session) next.ServeHTTP(w, r.WithContext(ctx)) }) }