Avoid referencing bad variable

This commit is contained in:
Maximilian Friedersdorff 2025-09-30 10:28:58 +01:00
parent c2e6612647
commit a90859e151

View file

@ -4,7 +4,6 @@ package middleware
import ( import (
"context" "context"
"crypto/rand" "crypto/rand"
"fmt"
"net/http" "net/http"
) )
@ -22,7 +21,7 @@ func NewSessionStore() SessionStore {
return SessionStore{sessions: make(map[string]Session, 10)} 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() sessionID := rand.Text()
s.sessions[sessionID] = Session{User: user} s.sessions[sessionID] = Session{User: user}
@ -32,6 +31,7 @@ func (s *SessionStore) Login(user string, w http.ResponseWriter) {
} }
http.SetCookie(w, &cookie) http.SetCookie(w, &cookie)
return sessionID
} }
func (s *SessionStore) Logout(w http.ResponseWriter, r *http.Request) { 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 { if err != nil {
user := r.Header.Get("X-Auth-Request-User") user := r.Header.Get("X-Auth-Request-User")
if user != "" { if user != "" {
s.Login(user, w) sessionID := s.Login(user, w)
nextWithSessionContext(w, r, next, user, sessionID)
} else { } else {
http.Redirect(w, r, "/login/", http.StatusFound) http.Redirect(w, r, "/login/", http.StatusFound)
return return
} }
} }
fmt.Println(sessionCookie.Value)
session, ok := s.sessions[sessionCookie.Value] session, ok := s.sessions[sessionCookie.Value]
// Session expired // Session expired
if !ok { if !ok {
user := r.Header.Get("X-Auth-Request-User") user := r.Header.Get("X-Auth-Request-User")
if user != "" { if user != "" {
s.Login(user, w) sessionID := s.Login(user, w)
nextWithSessionContext(w, r, next, user, sessionID)
} else { } else {
http.Redirect(w, r, "/login/", http.StatusFound) http.Redirect(w, r, "/login/", http.StatusFound)
return return
} }
} }
ctx := r.Context() nextWithSessionContext(w, r, next, session.User, sessionCookie.Value)
ctx = context.WithValue(
context.WithValue(
ctx,
ContextKey("user"),
session.User,
),
ContextKey("session"),
sessionCookie.Value,
)
next.ServeHTTP(w, r.WithContext(ctx))
}) })
} }
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))
}