package middleware import ( "context" "net/http" "git.leonardobishop.net/instancer/pkg/session" ) func MustAuthenticate(store *session.MemoryStore) func(http.HandlerFunc) http.HandlerFunc { return func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { sessionCookie, err := r.Cookie("session") if err != nil { w.Header().Add("HX-Redirect", "/auth") http.Redirect(w, r, "/auth", http.StatusFound) return } s := store.GetByToken(sessionCookie.Value) if s == nil { w.Header().Add("HX-Redirect", "/auth") http.Redirect(w, r, "/auth", http.StatusFound) return } ctx := context.WithValue(r.Context(), "session", s) next(w, r.WithContext(ctx)) } } }