Add structured logging and better error handling

This commit is contained in:
SirBlob committed 2026-11-01 13:50:26 -05:00
1 parent db4e3c9611
commit 68c7dd76f2
31 files changed
+640 -109

No files matched your search

+7 -3
View File
@@ -1,6 +1,8 @@
package server
import (
"fmt"
"log/slog"
"net"
"net/http"
"strings"
@@ -20,17 +22,18 @@ type sessionResponse struct {
func (server *Server) handleLogin(writer http.ResponseWriter, request *http.Request) {
client := server.clientAddress(request)
if !server.limiter.Allowed(client) {
slog.Warn("login blocked after too many failures", "client", client, "request_id", requestIDFrom(request))
writeError(writer, http.StatusTooManyRequests, "too many failed attempts, try again later")
return
}
var body loginRequest
if err := decodeJSON(request, &body); err != nil {
writeError(writer, http.StatusBadRequest, "invalid request body")
if !decodeBody(writer, request, &body) {
return
}
if !auth.CredentialsMatch(server.settings.Username, server.settings.Password, body.Username, body.Password) {
server.limiter.RecordFailure(client)
slog.Warn("login failed", "client", client, "username", body.Username, "request_id", requestIDFrom(request))
writeError(writer, http.StatusUnauthorized, "invalid username or password")
return
}
@@ -38,9 +41,10 @@ func (server *Server) handleLogin(writer http.ResponseWriter, request *http.Requ
server.limiter.Reset(client)
token, err := server.sessions.Create()
if err != nil {
writeError(writer, http.StatusInternalServerError, "could not create session")
writeFailure(writer, request, fmt.Errorf("could not create session: %w", err))
return
}
slog.Info("login succeeded", "client", client, "request_id", requestIDFrom(request))
http.SetCookie(writer, server.sessionCookie(token, int(server.settings.SessionTTL.Seconds())))
writeJSON(writer, http.StatusOK, sessionResponse{Authenticated: true})
}