c2edc586ef
Phase 14.B. The cookie already satisfied everything the __Host- prefix requires — Secure, Path=/, no Domain — but as a promise the server makes, not one the browser enforces. With the prefix the browser refuses to store a same-named cookie carrying a Domain attribute, which is the second lever the same-site neighbour from 14.A has: set selfpost_session for the parent domain, and the browser sends two cookies of that name, oldest first. r.Cookie returned that first one, so the admin logged in successfully and landed back on the login form, for as long as the planted cookie lived. The name has to stay conditional: __Host- is only valid on a Secure cookie, so with PANEL_COOKIE_SECURE=false the browser would discard the Set-Cookie and the dev instance would fail to log in with no visible reason. Hence the test on that branch specifically, not just the production one. requireAuth now reads r.Cookies() and refuses a request carrying more than one cookie of the name, with a log line naming the cause. That is the only place the overwrite becomes visible at all, and unlike the prefix it also works in the dev shape. Sign-out clears both names, so the upgrade does not leave the old cookie behind; it does sign the administrator out once, which costs nothing given sessions live in memory and die on restart anyway. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
39 lines
1004 B
Go
39 lines
1004 B
Go
package web
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
)
|
|
|
|
type ctxKey int
|
|
|
|
const usernameKey ctxKey = 0
|
|
|
|
// requireAuth wraps a handler so only requests with a valid session cookie
|
|
// reach it; everyone else is redirected to the login page. The authenticated
|
|
// username is stashed in the request context for downstream handlers.
|
|
func (s *Server) requireAuth(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
token, ok := s.sessionToken(r)
|
|
if !ok {
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
username, ok := s.sessions.Lookup(token)
|
|
if !ok {
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
ctx := context.WithValue(r.Context(), usernameKey, username)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// currentUser returns the authenticated username from the request context.
|
|
func currentUser(r *http.Request) string {
|
|
if v, ok := r.Context().Value(usernameKey).(string); ok {
|
|
return v
|
|
}
|
|
return ""
|
|
}
|