server: implement authentication
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user