summaryrefslogtreecommitdiff
path: root/internal/auth/handlers.go
diff options
context:
space:
mode:
authorPeter Stone <thepeterstone@gmail.com>2026-01-20 15:18:57 -1000
committerPeter Stone <thepeterstone@gmail.com>2026-01-20 15:18:57 -1000
commit78e8f597ff28f1b8406f5cfbf934adc22abdf85b (patch)
treef3b7dfff2c460e2d8752b61c131e80a73fa6b08d /internal/auth/handlers.go
parent08bbcf18b1207153983261652b4a43a9b36f386c (diff)
Add CSRF protection and auth unit tests
Add CSRF token middleware for state-changing request protection, integrate tokens into templates and HTMX headers, and add unit tests for authentication service and handlers. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Diffstat (limited to 'internal/auth/handlers.go')
-rw-r--r--internal/auth/handlers.go18
1 files changed, 11 insertions, 7 deletions
diff --git a/internal/auth/handlers.go b/internal/auth/handlers.go
index 17bcabd..c690d29 100644
--- a/internal/auth/handlers.go
+++ b/internal/auth/handlers.go
@@ -40,9 +40,11 @@ func (h *Handlers) HandleLoginPage(w http.ResponseWriter, r *http.Request) {
}
data := struct {
- Error string
+ Error string
+ CSRFToken string
}{
- Error: "",
+ Error: "",
+ CSRFToken: h.middleware.GetCSRFToken(r),
}
if err := h.templates.ExecuteTemplate(w, "login.html", data); err != nil {
@@ -62,14 +64,14 @@ func (h *Handlers) HandleLogin(w http.ResponseWriter, r *http.Request) {
password := r.FormValue("password")
if username == "" || password == "" {
- h.renderLoginError(w, "Username and password are required")
+ h.renderLoginError(w, r, "Username and password are required")
return
}
user, err := h.service.Authenticate(username, password)
if err != nil {
log.Printf("Login failed for user %s: %v", username, err)
- h.renderLoginError(w, "Invalid username or password")
+ h.renderLoginError(w, r, "Invalid username or password")
return
}
@@ -96,11 +98,13 @@ func (h *Handlers) HandleLogout(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
-func (h *Handlers) renderLoginError(w http.ResponseWriter, errorMsg string) {
+func (h *Handlers) renderLoginError(w http.ResponseWriter, r *http.Request, errorMsg string) {
data := struct {
- Error string
+ Error string
+ CSRFToken string
}{
- Error: errorMsg,
+ Error: errorMsg,
+ CSRFToken: h.middleware.GetCSRFToken(r),
}
w.WriteHeader(http.StatusUnauthorized)