server: implement authentication

This commit is contained in:
2026-05-17 03:22:03 +00:00
parent 8568b147bb
commit bd6c0bf211
7 changed files with 292 additions and 2 deletions
+28
View File
@@ -1,6 +1,7 @@
package api
import (
"context"
"errors"
"log/slog"
"net/http"
@@ -18,6 +19,33 @@ func Whoami(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("anonymous"))
return
}
slog.Debug("user: returning username", "userid", user.ID, "username", user.Name)
w.Write([]byte(user.Name))
}
func LoginCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Debug("user: entering LoginCtx middleware")
userID, ok := r.Context().Value(userIDKey).(uuid.UUID)
if !ok || userID == uuid.Nil {
slog.Debug("user: no user ID provided, assuming anonymous user")
next.ServeHTTP(w, r)
return
}
slog.Debug("user: fetching user by ID", "user ID", userID)
user, err := dbGetUser(userID.String())
if err != nil {
slog.Error("user: failed to fetch user by ID", "user ID", userID, "error", err)
render.Render(w, r, ErrNotFound)
return
}
slog.Debug("user: successfully fetched user", "user ID", user.ID, "username", user.Name)
ctx := context.WithValue(r.Context(), userKey{}, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func ListUsers(w http.ResponseWriter, r *http.Request) {