-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
280 lines (235 loc) · 8.57 KB
/
Copy pathserver.go
File metadata and controls
280 lines (235 loc) · 8.57 KB
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package main
import (
"fmt"
"net/http"
"os"
"runtime"
"runtime/debug"
"strings"
"time"
_ "embed"
"github.com/pilcrowonpaper/basic-example.auth.pilcrowonpaper.com/ratelimit"
"golang.org/x/sync/semaphore"
"zombiezen.com/go/sqlite"
"zombiezen.com/go/sqlite/sqlitex"
)
const databaseFilename = "data.db"
//go:embed schema.sql
var schemaSQLScript string
type serverStruct struct {
emailClient emailClientInterface
databaseReadConnectionPool *sqlitex.Pool
databaseWriteConnectionPool *sqlitex.Pool
cpuIntensiveSemaphore *semaphore.Weighted
https bool
logging serverLoggingStruct
userPasswordAuthenticationRateLimit *ratelimit.LimitStruct
emailAddressVerificationRateLimit *ratelimit.LimitStruct
userPasswordResetCodeVerificationRateLimit *ratelimit.LimitStruct
emailRateLimit *ratelimit.LimitStruct
requestRateLimit *ratelimit.LimitStruct
}
type serverLoggingStruct struct {
internalError bool
backgroundJob bool
actionResult bool
requestEmail bool
requestEvent bool
}
type serverFlagsStruct struct {
https bool
}
func createServer(emailClient emailClientInterface, flags serverFlagsStruct, logging serverLoggingStruct) (*serverStruct, error) {
databaseReadConnectionPool, err := sqlitex.NewPool(databaseFilename, sqlitex.PoolOptions{
Flags: sqlite.OpenReadWrite | sqlite.OpenWAL,
PoolSize: runtime.NumCPU(),
PrepareConn: func(conn *sqlite.Conn) error {
err := sqlitex.ExecuteTransient(conn, "PRAGMA foreign_keys = ON", nil)
if err != nil {
return fmt.Errorf("failed to enable foreign keys: %s", err.Error())
}
return nil
},
})
if err != nil {
return nil, fmt.Errorf("failed to create sqlite read connection pool: %s", err.Error())
}
databaseWriteConnectionPool, err := sqlitex.NewPool(databaseFilename, sqlitex.PoolOptions{
Flags: sqlite.OpenReadWrite | sqlite.OpenWAL,
PoolSize: 1,
PrepareConn: func(conn *sqlite.Conn) error {
err := sqlitex.ExecuteTransient(conn, "PRAGMA foreign_keys = ON", nil)
if err != nil {
return fmt.Errorf("failed to enable foreign keys: %s", err.Error())
}
return nil
},
})
if err != nil {
return nil, fmt.Errorf("failed to create sqlite write connection pool: %s", err.Error())
}
cpuIntensiveSemaphore := semaphore.NewWeighted(int64(runtime.NumCPU()))
userPasswordAuthenticationRateLimit := ratelimit.NewLimit(1_000, 5, time.Minute)
emailAddressVerificationRateLimit := ratelimit.NewLimit(1_000, 5, time.Minute)
userPasswordResetCodeVerificationRateLimit := ratelimit.NewLimit(1_000, 5, time.Minute)
emailRateLimit := ratelimit.NewLimit(1_000, 5, 30*time.Minute)
requestRateLimit := ratelimit.NewLimit(10_000, 100, time.Second)
server := &serverStruct{
emailClient: emailClient,
databaseReadConnectionPool: databaseReadConnectionPool,
databaseWriteConnectionPool: databaseWriteConnectionPool,
cpuIntensiveSemaphore: cpuIntensiveSemaphore,
https: flags.https,
logging: logging,
userPasswordAuthenticationRateLimit: userPasswordAuthenticationRateLimit,
emailAddressVerificationRateLimit: emailAddressVerificationRateLimit,
userPasswordResetCodeVerificationRateLimit: userPasswordResetCodeVerificationRateLimit,
emailRateLimit: emailRateLimit,
requestRateLimit: requestRateLimit,
}
return server, nil
}
func (server *serverStruct) start(port int) error {
go server.clearDataBackgroundJob()
httpSever := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: http.MaxBytesHandler(http.HandlerFunc(server.handleRequest), 1024*16),
MaxHeaderBytes: 1024 * 16,
ReadTimeout: 30 * time.Second,
}
err := httpSever.ListenAndServe()
if err != nil {
return fmt.Errorf("failed to listen and serve: %s", err.Error())
}
return nil
}
func (server *serverStruct) handleRequest(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
// Just kill the server if it panics
stack := debug.Stack()
fmt.Fprintf(os.Stderr, "%v\n", err)
fmt.Fprintf(os.Stderr, "%s\n", stack)
os.Exit(1)
}
}()
requestId := r.Header.Get("X-Railway-Request-Id")
if requestId == "" {
requestId = generateLongItemId()
}
clientIPAddress := r.Header.Get("X-Real-IP")
if clientIPAddress != "" {
rateLimitAllowed := server.requestRateLimit.Consume(clientIPAddress)
if !rateLimitAllowed {
w.WriteHeader(429)
return
}
}
pathParts := strings.Split(r.URL.Path, "/")[1:]
// Remove single trailing slash
if len(pathParts) > 0 && pathParts[len(pathParts)-1] == "" {
pathParts = pathParts[:len(pathParts)-1]
}
// GET /
if len(pathParts) == 0 && r.Method == "GET" {
server.homePageRoute(w, r, requestId, clientIPAddress)
return
}
// /sign-up
if len(pathParts) > 0 && pathParts[0] == "sign-up" {
// GET /sign-up
if len(pathParts) == 1 && r.Method == "GET" {
server.signUpPageRoute(w, r, requestId, clientIPAddress)
return
}
// GET /sign-up/verify-email-address
if len(pathParts) == 2 && pathParts[1] == "verify-email-address" && r.Method == "GET" {
server.signUpVerifyEmailAddressPageRoute(w, r, requestId, clientIPAddress)
return
}
// GET /sign-up/set-password
if len(pathParts) == 2 && pathParts[1] == "set-password" && r.Method == "GET" {
server.signUpSetPasswordPageRoute(w, r, requestId, clientIPAddress)
return
}
}
// GET /sign-in
if len(pathParts) == 1 && pathParts[0] == "sign-in" && r.Method == "GET" {
server.signInPageRoute(w, r, requestId, clientIPAddress)
return
}
// GET /account
if len(pathParts) == 1 && pathParts[0] == "account" && r.Method == "GET" {
server.accountPageRoute(w, r, requestId, clientIPAddress)
return
}
// /update-password
if len(pathParts) > 0 && pathParts[0] == "update-password" {
// GET /update-password/verify-password
if len(pathParts) == 2 && pathParts[1] == "verify-password" && r.Method == "GET" {
server.updatePasswordVerifyPasswordPageRoute(w, r, requestId, clientIPAddress)
return
}
// GET /update-password/set-new-password
if len(pathParts) == 2 && pathParts[1] == "set-new-password" && r.Method == "GET" {
server.updatePasswordSetNewPasswordPageRoute(w, r, requestId, clientIPAddress)
return
}
}
// /update-email-address
if len(pathParts) > 0 && pathParts[0] == "update-email-address" {
// GET /update-email-address/verify-password
if len(pathParts) == 2 && pathParts[1] == "verify-password" && r.Method == "GET" {
server.updateEmailAddressVerifyPasswordPageRoute(w, r, requestId, clientIPAddress)
return
}
// GET /update-email-address/set-new-email-address
if len(pathParts) == 2 && pathParts[1] == "set-new-email-address" && r.Method == "GET" {
server.updateEmailAddressSetNewEmailAddressPageRoute(w, r, requestId, clientIPAddress)
return
}
// GET /update-email-address/verify-new-email-address
if len(pathParts) == 2 && pathParts[1] == "verify-new-email-address" && r.Method == "GET" {
server.updateEmailAddressVerifyNewEmailAddressPageRoute(w, r, requestId, clientIPAddress)
return
}
}
// /delete-account
if len(pathParts) > 0 && pathParts[0] == "delete-account" {
// GET /delete-account/verify-password
if len(pathParts) == 2 && pathParts[1] == "verify-password" && r.Method == "GET" {
server.deleteAccountVerifyPasswordPageRoute(w, r, requestId, clientIPAddress)
return
}
// GET /delete-account/confirm
if len(pathParts) == 2 && pathParts[1] == "confirm" && r.Method == "GET" {
server.deleteAccountConfirmPageRoute(w, r, requestId, clientIPAddress)
return
}
}
// /reset-password
if len(pathParts) > 0 && pathParts[0] == "reset-password" {
// GET /reset-password
if len(pathParts) == 1 && r.Method == "GET" {
server.resetPasswordPageRoute(w, requestId, clientIPAddress)
return
}
// GET /reset-password/verify-email-code
if len(pathParts) == 2 && pathParts[1] == "verify-email-code" && r.Method == "GET" {
server.resetPasswordVerifyEmailCodePageRoute(w, r, requestId, clientIPAddress)
return
}
// GET /reset-password/set-new-password
if len(pathParts) == 2 && pathParts[1] == "set-new-password" && r.Method == "GET" {
server.resetPasswordSetNewPasswordPageRoute(w, r, requestId, clientIPAddress)
return
}
}
// POST /action
if len(pathParts) == 1 && pathParts[0] == "action" && r.Method == "POST" {
server.actionRoute(w, r, requestId, clientIPAddress)
return
}
w.WriteHeader(404)
w.Write([]byte("The page you're looking for doesn't exist."))
}