summaryrefslogtreecommitdiffstats
path: root/web/middleware/auth.go
blob: fcba3b7dda4fcf198e5a742daa4c5bca2be493b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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))
		}
	}
}