From 799bf784aa95ca2681d4a2f4b9c787e86e73b9e3 Mon Sep 17 00:00:00 2001 From: William P Date: Tue, 8 Apr 2025 21:00:33 -0400 Subject: [PATCH] allow LoginCtx to handle anonymous users --- api/user.go | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/api/user.go b/api/user.go index 737c940..7841215 100644 --- a/api/user.go +++ b/api/user.go @@ -32,28 +32,29 @@ func UserCtx(next http.Handler) http.Handler { func Whoami(w http.ResponseWriter, r *http.Request) { user, ok := r.Context().Value(userKey{}).(*User) - if !ok { - w.Write([]byte("undefined")) - return - } else { - w.Write([]byte(user.Name)) + if !ok || user == nil { + // Anonymous user + w.Write([]byte("anonymous")) return } + + w.Write([]byte(user.Name)) } func LoginCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var user *User - var err error - - if username := r.Context().Value(usernameKey).(string); username != "" { - user, err = dbGetUserByName(username) - } else { - render.Render(w, r, ErrNotFound) + // Try to retrieve username from context + username, ok := r.Context().Value(usernameKey).(string) + if !ok || username == "" { + // No username provided, assume it's an anonymous user + next.ServeHTTP(w, r) return } + // Lookup user in the database + user, err := dbGetUserByName(username) if err != nil { + // If user is specified and not found, throw an error render.Render(w, r, ErrNotFound) return }