From a90859e151be149a87fa69c5590740295126e56c Mon Sep 17 00:00:00 2001 From: Maximilian Friedersdorff Date: Tue, 30 Sep 2025 10:28:58 +0100 Subject: [PATCH] Avoid referencing bad variable --- internal/middleware/session.go | 40 +++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/internal/middleware/session.go b/internal/middleware/session.go index 6de3100..4f960f6 100644 --- a/internal/middleware/session.go +++ b/internal/middleware/session.go @@ -4,7 +4,6 @@ package middleware import ( "context" "crypto/rand" - "fmt" "net/http" ) @@ -22,7 +21,7 @@ func NewSessionStore() SessionStore { return SessionStore{sessions: make(map[string]Session, 10)} } -func (s *SessionStore) Login(user string, w http.ResponseWriter) { +func (s *SessionStore) Login(user string, w http.ResponseWriter) string { sessionID := rand.Text() s.sessions[sessionID] = Session{User: user} @@ -32,6 +31,7 @@ func (s *SessionStore) Login(user string, w http.ResponseWriter) { } http.SetCookie(w, &cookie) + return sessionID } func (s *SessionStore) Logout(w http.ResponseWriter, r *http.Request) { @@ -53,39 +53,43 @@ func (s *SessionStore) AsMiddleware(next http.Handler) http.Handler { if err != nil { user := r.Header.Get("X-Auth-Request-User") if user != "" { - s.Login(user, w) + sessionID := s.Login(user, w) + nextWithSessionContext(w, r, next, user, sessionID) } else { http.Redirect(w, r, "/login/", http.StatusFound) return } } - fmt.Println(sessionCookie.Value) - session, ok := s.sessions[sessionCookie.Value] // Session expired if !ok { user := r.Header.Get("X-Auth-Request-User") if user != "" { - s.Login(user, w) + sessionID := s.Login(user, w) + nextWithSessionContext(w, r, next, user, sessionID) } else { http.Redirect(w, r, "/login/", http.StatusFound) return } } - ctx := r.Context() - ctx = context.WithValue( - context.WithValue( - ctx, - ContextKey("user"), - session.User, - ), - ContextKey("session"), - sessionCookie.Value, - ) - - next.ServeHTTP(w, r.WithContext(ctx)) + nextWithSessionContext(w, r, next, session.User, sessionCookie.Value) }) } + +func nextWithSessionContext(w http.ResponseWriter, r *http.Request, next http.Handler, user string, sessionID string) { + ctx := r.Context() + ctx = context.WithValue( + context.WithValue( + ctx, + ContextKey("user"), + user, + ), + ContextKey("session"), + sessionID, + ) + + next.ServeHTTP(w, r.WithContext(ctx)) +}