-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrespond.go
More file actions
179 lines (153 loc) · 4.59 KB
/
Copy pathrespond.go
File metadata and controls
179 lines (153 loc) · 4.59 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
package main
import (
"encoding/json"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
)
// --- Content negotiation ---
func wantsJSON(r *http.Request) bool {
return strings.Contains(r.Header.Get("Accept"), "application/json")
}
func respondSuccess(w http.ResponseWriter, r *http.Request, status int, msg, redirect string) {
if wantsJSON(r) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]any{"success": true, "message": msg})
} else {
http.Redirect(w, r, redirect, http.StatusFound)
}
}
func respondError(w http.ResponseWriter, r *http.Request, status int, code, msg string) {
if wantsJSON(r) {
jsonError(w, status, code, msg)
} else {
http.Redirect(w, r, "/#error", http.StatusFound)
}
}
func jsonError(w http.ResponseWriter, status int, code, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]string{"error": msg, "code": code})
}
func jsonOK(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
func jsonCreated(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(v)
}
// --- Request parsing ---
const maxBodySize = 1 << 20 // 1 MB
func parseRegistration(r *http.Request) (email, password, token string) {
r.Body = http.MaxBytesReader(nil, r.Body, maxBodySize)
ct := r.Header.Get("Content-Type")
if strings.Contains(ct, "application/json") {
var body struct {
Email string `json:"email"`
Password string `json:"password"`
RegistrationToken string `json:"registrationToken"`
}
json.NewDecoder(r.Body).Decode(&body)
return strings.ToLower(strings.TrimSpace(body.Email)), body.Password, body.RegistrationToken
}
r.ParseForm()
return strings.ToLower(strings.TrimSpace(r.FormValue("email"))), r.FormValue("password"), r.FormValue("registrationToken")
}
func parsePasswordChange(r *http.Request) (current, next string) {
r.Body = http.MaxBytesReader(nil, r.Body, maxBodySize)
ct := r.Header.Get("Content-Type")
if strings.Contains(ct, "application/json") {
var body struct {
CurrentPassword string `json:"currentPassword"`
NewPassword string `json:"newPassword"`
}
json.NewDecoder(r.Body).Decode(&body)
return body.CurrentPassword, body.NewPassword
}
r.ParseForm()
return r.FormValue("currentPassword"), r.FormValue("newPassword")
}
// GET /health
func handleHealth(w http.ResponseWriter, r *http.Request) {
status := "ok"
if err := store.Ping(); err != nil {
status = "degraded"
w.WriteHeader(http.StatusServiceUnavailable)
}
jsonOK(w, map[string]any{"status": status, "timestamp": nowUnix()})
}
// --- Cookie helpers ---
func setAuthCookie(w http.ResponseWriter, name, value string, maxAge time.Duration) {
http.SetCookie(w, &http.Cookie{ // #nosec G124 -- Secure set dynamically via cfg.CookieSecure
Name: name,
Value: value,
Path: "/",
MaxAge: int(maxAge.Seconds()),
HttpOnly: true,
Secure: cfg.CookieSecure,
SameSite: http.SameSiteStrictMode,
})
}
func deleteAuthCookie(w http.ResponseWriter, name string) {
http.SetCookie(w, &http.Cookie{ // #nosec G124 -- deletion cookie; Secure set dynamically
Name: name,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
Secure: cfg.CookieSecure,
SameSite: http.SameSiteStrictMode,
})
}
func setTokenCookies(w http.ResponseWriter, uid int, sid string) error {
access, err := signToken(uid, sid, "access", cfg.AccessSecret, accessExpiry)
if err != nil {
return err
}
refresh, err := signRefreshToken(uid, sid, cfg.RefreshSecret, 0) // gen=0 matches initial session refresh_gen
if err != nil {
return err
}
setAuthCookie(w, "access_token", access, accessExpiry)
setAuthCookie(w, "refresh_token", refresh, refreshExpiry)
return nil
}
func clearTokenCookies(w http.ResponseWriter) {
deleteAuthCookie(w, "access_token")
deleteAuthCookie(w, "refresh_token")
}
// --- IP helpers ---
func stripPort(addr string) string {
if i := strings.LastIndex(addr, ":"); i >= 0 {
return addr[:i]
}
return addr
}
func connIP(r *http.Request) string {
return stripPort(r.RemoteAddr)
}
func clientIP(r *http.Request) string {
return connIP(r)
}
// --- Parsing helpers ---
func numericID(v any) (int, bool) {
switch id := v.(type) {
case float64:
return int(id), true
case string:
n, err := strconv.Atoi(id)
return n, err == nil
}
return 0, false
}
// --- Error logging ---
func logError(op string, err error) {
if err != nil {
slog.Error(op, "error", err)
}
}