diff options
Diffstat (limited to 'web/middleware/auth.go')
| -rw-r--r-- | web/middleware/auth.go | 32 |
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)) + } + } +} |
