From 03cd6bdfbd473dba3f3dc50a1b15e389aac5bc70 Mon Sep 17 00:00:00 2001 From: Leonardo Bishop Date: Wed, 7 Jan 2026 23:39:53 +0000 Subject: Initial commit --- web/middleware/auth.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 web/middleware/auth.go (limited to 'web/middleware') diff --git a/web/middleware/auth.go b/web/middleware/auth.go new file mode 100644 index 0000000..fcba3b7 --- /dev/null +++ b/web/middleware/auth.go @@ -0,0 +1,32 @@ +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)) + } + } +} -- cgit v1.2.3-70-g09d2