summaryrefslogtreecommitdiffstats
path: root/web/middleware
diff options
context:
space:
mode:
authorLeonardo Bishop <me@leonardobishop.net>2026-01-07 23:39:53 +0000
committerLeonardo Bishop <me@leonardobishop.net>2026-01-07 23:39:53 +0000
commit03cd6bdfbd473dba3f3dc50a1b15e389aac5bc70 (patch)
tree5fea2b1840e298aaab953add749fb9226bd4a710 /web/middleware
Initial commit
Diffstat (limited to 'web/middleware')
-rw-r--r--web/middleware/auth.go32
1 files changed, 32 insertions, 0 deletions
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))
+ }
+ }
+}