summaryrefslogtreecommitdiff
path: root/pkg/webui/sessions.go
blob: 6d492d57ad903f3acfe441ed241a3171bf54348a (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
package webui

import (
	"context"
	"errors"
	"fmt"
	"net/http"

	"git.adyxax.org/adyxax/tfstated/pkg/database"
	"git.adyxax.org/adyxax/tfstated/pkg/model"
)

const cookieName = "tfstated"

func sessionsMiddleware(db *database.DB) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			cookie, err := r.Cookie(cookieName)
			if err != nil && !errors.Is(err, http.ErrNoCookie) {
				errorResponse(w, http.StatusInternalServerError, fmt.Errorf("failed to get request cookie \"%s\": %w", cookieName, err))
				return
			}
			if err == nil {
				if len(cookie.Value) != 36 {
					http.SetCookie(w, &http.Cookie{
						Name:     cookieName,
						Value:    "",
						Quoted:   false,
						Path:     "/",
						MaxAge:   0, // remove invalid cookie
						HttpOnly: true,
						SameSite: http.SameSiteStrictMode,
						Secure:   true,
					})
				} else {
					session, err := db.LoadSessionById(cookie.Value)
					if err != nil {
						errorResponse(w, http.StatusInternalServerError, err)
						return
					}
					if !session.IsExpired() {
						if err := db.TouchSession(cookie.Value); err != nil {
							errorResponse(w, http.StatusInternalServerError, err)
							return
						}
						ctx := context.WithValue(r.Context(), model.SessionContextKey{}, session)
						next.ServeHTTP(w, r.WithContext(ctx))
						return
					}
				}
			}
			next.ServeHTTP(w, r)
		})
	}
}