-
-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathmw.go
176 lines (153 loc) · 4.6 KB
/
mw.go
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright © 2019 Martin Tournoij – This file is part of GoatCounter and
// published under the terms of a slightly modified EUPL v1.2 license, which can
// be found in the LICENSE file or at https://license.goatcounter.com
package handlers
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"time"
"zgo.at/goatcounter"
"zgo.at/goatcounter/cfg"
"zgo.at/goatcounter/cron"
"zgo.at/guru"
"zgo.at/json"
"zgo.at/zdb"
"zgo.at/zhttp"
"zgo.at/zhttp/auth"
"zgo.at/zlog"
"zgo.at/zstd/znet"
"zgo.at/zstd/zstring"
)
var (
redirect = func(w http.ResponseWriter, r *http.Request) error {
zhttp.Flash(w, "Need to log in")
return guru.Errorf(303, "/user/new")
}
loggedIn = auth.Filter(func(w http.ResponseWriter, r *http.Request) error {
u := goatcounter.GetUser(r.Context())
if u != nil && u.ID > 0 {
return nil
}
return redirect(w, r)
})
loggedInOrPublic = auth.Filter(func(w http.ResponseWriter, r *http.Request) error {
u := goatcounter.GetUser(r.Context())
if (u != nil && u.ID > 0) || Site(r.Context()).Settings.Public {
return nil
}
return redirect(w, r)
})
noSubSites = auth.Filter(func(w http.ResponseWriter, r *http.Request) error {
if Site(r.Context()).Parent == nil ||
*Site(r.Context()).Parent == 0 {
return nil
}
zlog.FieldsRequest(r).Errorf("noSubSites")
return guru.Errorf(403, "child sites can't access this")
})
adminOnly = auth.Filter(func(w http.ResponseWriter, r *http.Request) error {
if Site(r.Context()).Admin() {
return nil
}
return guru.Errorf(404, "")
})
keyAuth = auth.Add(func(ctx context.Context, key string) (auth.User, error) {
u := &goatcounter.User{}
err := u.ByTokenAndSite(ctx, key)
return u, err
})
)
type statusWriter interface{ Status() int }
func addctx(db zdb.DB, loadSite bool) func(http.Handler) http.Handler {
started := goatcounter.Now()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.URL.Path == "/status" {
j, err := json.Marshal(map[string]string{
"uptime": goatcounter.Now().Sub(started).String(),
"version": cfg.Version,
"last_persisted_at": cron.LastMemstore.Get().Format(time.RFC3339Nano),
})
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(j)
return
}
// Add timeout on non-admin pages.
t := 3
switch {
case strings.HasPrefix(r.URL.Path, "/admin"):
t = 120
case r.URL.Path == "/":
t = 11
}
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(r.Context(), time.Duration(t)*time.Second)
defer func() {
cancel()
if ctx.Err() == context.DeadlineExceeded {
if ww, ok := w.(statusWriter); !ok || ww.Status() == 0 {
w.WriteHeader(http.StatusGatewayTimeout)
w.Write([]byte("Server timed out"))
}
}
}()
// Add database.
*r = *r.WithContext(zdb.WithDB(ctx, db))
if !cfg.Prod {
if c, _ := r.Cookie("debug-explain"); c != nil {
*r = *r.WithContext(zdb.WithDB(ctx, zdb.NewExplainDB(db, os.Stdout, c.Value)))
}
}
// Load site from subdomain.
if loadSite {
var s goatcounter.Site
err := s.ByHost(r.Context(), r.Host)
if err != nil && cfg.Serve {
// If there's just one site then we can just serve that;
// most people probably have just one site so it's all
// grand.
//
// Do print a warning in the console though.
var sites goatcounter.Sites
err2 := sites.UnscopedList(r.Context())
if err2 == nil && len(sites) == 1 {
s = sites[0]
err = nil
if r.URL.Path == "/" {
zlog.Printf(zstring.WordWrap(fmt.Sprintf(""+
"accessing the site on domain %q, but the configured domain is %q; "+
"this will work fine as long as you only have one site, but you *need* to use the "+
"configured domain if you add a second site so GoatCounter will know which site to use.",
znet.RemovePort(r.Host), *s.Cname), strings.Repeat(" ", 25), 55))
}
}
if err2 == nil && len(sites) == 0 {
err = guru.Errorf(400, ""+
`no sites created yet; create a new site from the commandline with `+
`"goatcounter create -domain [..] -email [..]"`)
}
}
if err != nil {
if zdb.ErrNoRows(err) {
err = guru.Errorf(400, "no site at this domain (%q)", r.Host)
} else {
zlog.FieldsRequest(r).Error(err)
}
zhttp.ErrPage(w, r, err)
return
}
*r = *r.WithContext(goatcounter.WithSite(r.Context(), &s))
}
next.ServeHTTP(w, r)
})
}
}