File size: 3,148 Bytes
84ffb7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package web

import (
	"context"
	"log/slog"
	"net/http"
	"time"

	"pageturner/internal/auth"
	"pageturner/internal/config"
	"pageturner/internal/logs"
	"pageturner/internal/models"
)

type ctxKey int

const (
	userKey ctxKey = iota
	csrfKey
)

// Server wires routes, middleware and handlers together.
type Server struct {
	cfg     config.Config
	store   *models.Store
	handler http.Handler
	log     *slog.Logger
	hub     *logs.Hub
}

func NewServer(cfg config.Config, store *models.Store, log *slog.Logger, hub *logs.Hub) *Server {
	s := &Server{
		cfg:   cfg,
		store: store,
		log:   log,
		hub:   hub,
	}
	templateLog = log
	s.routes(http.NewServeMux())
	return s
}

func (s *Server) routes(mux *http.ServeMux) {
	// Public
	mux.HandleFunc("GET /healthz", s.handleHealth)
	mux.HandleFunc("GET /{$}", s.handleHome)
	mux.HandleFunc("GET /login", s.handleLoginGet)
	mux.HandleFunc("POST /login", s.handleLoginPost)
	mux.Handle("GET /static/", http.StripPrefix("/static/", staticFiles()))

	// Authenticated
	mux.HandleFunc("POST /logout", s.handleLogout)
	mux.HandleFunc("GET /markitdown", s.handleMarkitdown)
	mux.HandleFunc("GET /markitdown/stream", s.handleMarkitdownStream)
	mux.HandleFunc("GET /logs/stream", s.handleLogStream)

	// Wrap the whole router; the last middleware listed runs first, so the
	// execution order is: requireAuth → csrf → requestLog → recoverPanic.
	s.handler = wrap(mux, s.recoverPanic, s.requestLog, s.csrf, s.requireAuth)
}

// Handler returns the fully wrapped http.Handler.
func (s *Server) Handler() http.Handler { return s.handler }

// wrap nests middlewares inside-out: each one wraps the previous result, so
// the last listed middleware runs first for every request.
func wrap(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler {
	for _, mw := range mws {
		h = mw(h)
	}
	return h
}

// --- context helpers ---

func contextWithUser(ctx context.Context, u models.User) context.Context {
	return context.WithValue(ctx, userKey, u)
}

func userFrom(r *http.Request) models.User {
	u, _ := r.Context().Value(userKey).(models.User)
	return u
}

func contextWithCSRF(ctx context.Context, token string) context.Context {
	return context.WithValue(ctx, csrfKey, token)
}

func csrfFrom(r *http.Request) string {
	t, _ := r.Context().Value(csrfKey).(string)
	return t
}

// --- small helpers ---

func (s *Server) sessionCookie(token string, maxAge int) *http.Cookie {
	return &http.Cookie{
		Name:     "session",
		Value:    token,
		Path:     "/",
		HttpOnly: true,
		Secure:   s.cfg.CookieSecure(),
		SameSite: http.SameSiteLaxMode,
		MaxAge:   maxAge,
	}
}

func (s *Server) csrfCookie(token string, maxAge int) *http.Cookie {
	return &http.Cookie{
		Name:     "csrf",
		Value:    token,
		Path:     "/",
		HttpOnly: true,
		Secure:   s.cfg.CookieSecure(),
		SameSite: http.SameSiteLaxMode,
		MaxAge:   maxAge,
	}
}

func (s *Server) ttlSeconds() int {
	return int(s.cfg.SessionTTL / time.Second)
}

func isHTMX(r *http.Request) bool {
	return r.Header.Get("HX-Request") == "true"
}

func newCSRFOrEmpty() string {
	t, err := auth.NewCSRF()
	if err != nil {
		return ""
	}
	return t
}