auth.go
346 lines1
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package controllers
import (
"cmp"
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
"congo.gg/pkg/application"
"congo.gg/pkg/database"
"congo.gg/dev/internal"
"congo.gg/dev/models"
)
var (
jwtSecret = []byte(cmp.Or(os.Getenv("AUTH_SECRET"), "dev-secret"))
LoginRedirect = "/"
users *database.Collection[models.User]
loginLimiter = newRateLimiter(5, time.Minute)
)
func Auth() (string, *AuthController) {
users = models.Users
return "auth", &AuthController{}
}
type AuthController struct {
application.BaseController
}
func (c *AuthController) Setup(app *application.App) {
c.BaseController.Setup(app)
http.Handle("GET /login", app.Serve("login.html", nil))
http.Handle("POST /login", app.Method(c, "Login", nil))
http.HandleFunc("GET /setup", func(w http.ResponseWriter, r *http.Request) {
if count, _ := users.Count(""); count > 0 {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
app.Serve("setup.html", nil).ServeHTTP(w, r)
})
http.Handle("POST /setup", app.Method(c, "CreateAccount", nil))
http.Handle("POST /logout", app.Method(c, "Logout", nil))
}
func (c AuthController) Handle(r *http.Request) application.Controller {
c.Request = r
return &c
}
// RequireAuth returns a bouncer that redirects unauthenticated requests.
func RequireAuth() application.Bouncer {
return func(app *application.App, w http.ResponseWriter, r *http.Request) bool {
count, _ := users.Count("")
if count == 0 {
http.Redirect(w, r, "/setup", http.StatusSeeOther)
return false
}
if GetUser(r) == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return false
}
return true
}
}
// AuthMiddleware wraps an http.Handler with auth checking.
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if GetUser(r) == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
// GetUser extracts the authenticated user from the request's session cookie.
func GetUser(r *http.Request) *models.User {
cookie, err := r.Cookie("session")
if err != nil || cookie.Value == "" {
return nil
}
token, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (any, error) {
return jwtSecret, nil
})
if err != nil || !token.Valid {
return nil
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil
}
userID, _ := claims["user_id"].(string)
if userID == "" {
return nil
}
user, err := users.Get(userID)
if err != nil {
return nil
}
return user
}
func setSessionCookie(w http.ResponseWriter, r *http.Request, userID string) error {
jti := make([]byte, 16)
if _, err := rand.Read(jti); err != nil {
return fmt.Errorf("generating token ID: %w", err)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userID,
"exp": time.Now().Add(30 * 24 * time.Hour).Unix(),
"iat": time.Now().Unix(),
"jti": hex.EncodeToString(jti),
})
tokenString, err := token.SignedString(jwtSecret)
if err != nil {
return fmt.Errorf("signing token: %w", err)
}
secure := r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https"
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: tokenString,
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteLaxMode,
MaxAge: 30 * 24 * 60 * 60,
})
return nil
}
func clearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: "",
Path: "/",
HttpOnly: true,
MaxAge: -1,
})
}
// Template methods
func (c *AuthController) NeedsSetup() bool {
count, _ := users.Count("")
return count == 0
}
func (c *AuthController) HasError() bool {
return c.QueryParam("error", "") != ""
}
func (c *AuthController) CurrentUser() *models.User {
return GetUser(c.Request)
}
// Handlers
func (c *AuthController) Login(w http.ResponseWriter, r *http.Request) {
count, _ := users.Count("")
if count == 0 {
http.Redirect(w, r, "/setup", http.StatusSeeOther)
return
}
ip := r.RemoteAddr
if !loginLimiter.allow(ip) {
go models.Activities.Insert(&models.Activity{Action: "signin_rate_limited", Detail: "Rate limited login from " + ip})
http.Redirect(w, r, "/login?error=1", http.StatusSeeOther)
return
}
username := r.FormValue("username")
password := r.FormValue("password")
user, err := users.First("WHERE Username = ?", username)
if err != nil || user == nil {
http.Redirect(w, r, "/login?error=1", http.StatusSeeOther)
return
}
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)) != nil {
http.Redirect(w, r, "/login?error=1", http.StatusSeeOther)
return
}
if err := setSessionCookie(w, r, user.ID); err != nil {
c.RenderError(w, r, err)
return
}
go models.Activities.Insert(&models.Activity{Action: "signin", Detail: "Signed in as " + username})
http.Redirect(w, r, LoginRedirect, http.StatusSeeOther)
}
func (c *AuthController) CreateAccount(w http.ResponseWriter, r *http.Request) {
count, _ := users.Count("")
if count > 0 {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
// Validate setup token if it exists
if tokenData, err := os.ReadFile("/opt/congo-dev-setup-token"); err == nil {
expected := strings.TrimSpace(string(tokenData))
provided := strings.TrimSpace(r.FormValue("token"))
if expected != "" && provided != expected {
c.RenderError(w, r, fmt.Errorf("invalid setup token"))
return
}
}
username := r.FormValue("username")
password := r.FormValue("password")
confirm := r.FormValue("confirm")
if username == "" || password == "" {
c.RenderError(w, r, fmt.Errorf("username and password are required"))
return
}
if password != confirm {
c.RenderError(w, r, fmt.Errorf("passwords do not match"))
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
c.RenderError(w, r, err)
return
}
user := &models.User{
Username: username,
PasswordHash: string(hash),
}
id, err := users.Insert(user)
if err != nil {
c.RenderError(w, r, err)
return
}
if err := setSessionCookie(w, r, id); err != nil {
c.RenderError(w, r, err)
return
}
// Invalidate setup token now that account exists
os.Remove("/opt/congo-dev-setup-token")
// Set up domain if provided (basic validation)
if domain := strings.TrimSpace(r.FormValue("domain")); domain != "" && strings.Contains(domain, ".") && !strings.ContainsAny(domain, " /\\@") {
go func() {
if err := internal.SetupDomain(domain); err != nil {
log.Printf("domain setup: %v", err)
}
}()
}
go models.Activities.Insert(&models.Activity{Action: "signup", Detail: "Created account " + username})
http.Redirect(w, r, LoginRedirect, http.StatusSeeOther)
}
func (c *AuthController) Logout(w http.ResponseWriter, r *http.Request) {
clearSessionCookie(w)
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
// rateLimiter tracks attempts per key within a time window.
type rateLimiter struct {
mu sync.Mutex
attempts map[string][]time.Time
limit int
window time.Duration
}
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
rl := &rateLimiter{
attempts: make(map[string][]time.Time),
limit: limit,
window: window,
}
go func() {
for range time.Tick(5 * time.Minute) {
rl.mu.Lock()
cutoff := time.Now().Add(-rl.window)
for k, times := range rl.attempts {
var valid []time.Time
for _, t := range times {
if t.After(cutoff) {
valid = append(valid, t)
}
}
if len(valid) == 0 {
delete(rl.attempts, k)
} else {
rl.attempts[k] = valid
}
}
rl.mu.Unlock()
}
}()
return rl
}
func (rl *rateLimiter) allow(key string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
cutoff := now.Add(-rl.window)
var valid []time.Time
for _, t := range rl.attempts[key] {
if t.After(cutoff) {
valid = append(valid, t)
}
}
if len(valid) >= rl.limit {
rl.attempts[key] = valid
return false
}
// Cap total tracked keys to prevent memory growth under DDoS
if len(rl.attempts) > 10000 {
return false
}
rl.attempts[key] = append(valid, now)
return true
}