summaryrefslogtreecommitdiffstats
path: root/web/middleware/auth.go
blob: 5feccfe7908141c30dc2163e82389580868684a0 (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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package middleware

import (
	"context"
	"errors"
	"html/template"
	"log/slog"
	"net/http"
	"net/url"

	"git.leonardobishop.net/instancer/pkg/auth"
	"git.leonardobishop.net/instancer/pkg/session"
)

func MustAuthenticate(tmpl *template.Template, store *session.MemoryStore, authProvider *auth.OIDCAuthProvider) func(http.HandlerFunc) http.HandlerFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			sessionCookie, err := r.Cookie("instancer-session")
			if err != nil {
				http.Redirect(w, r, "/auth", http.StatusFound)
				return
			}

			s := store.GetByToken(sessionCookie.Value)
			if s == nil {
				http.Redirect(w, r, "/auth?error="+url.QueryEscape("Session does not exist"), http.StatusFound)
				return
			}

			err = authProvider.UpdateUserInfo(r.Context(), s)
			if err != nil {
				if errors.Is(err, auth.ErrInvalidToken) {
					http.Redirect(w, r, "/auth?error="+url.QueryEscape("OIDC authentication has expired"), http.StatusFound)
					return
				}
				slog.Error("error updating user info", "cause", err)
				w.Header().Add("HX-Redirect", "/problem")
				tmpl.ExecuteTemplate(w, "problem.html", struct {
					Error      string
					ShowLogout bool
				}{
					Error:      "There was a problem fetching your user info. Try again later.",
					ShowLogout: true,
				})
				return
			}

			if s.TeamID == "" || s.TeamName == "" {
				w.Header().Add("HX-Redirect", "/problem")
				tmpl.ExecuteTemplate(w, "problem.html", struct {
					Error      string
					ShowLogout bool
				}{
					Error:      "You are not part of a team. Please join a team and then refresh this page.",
					ShowLogout: true,
				})
				return
			}

			ctx := context.WithValue(r.Context(), "session", s)

			next(w, r.WithContext(ctx))
		}
	}
}