Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions auth/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ func (m *AuthenticationMiddleware) Wrap(next http.Handler) http.Handler {

newRequest := r
if user != nil {
if event := log.EventFromContext(r.Context()); event != nil {
event.AddAttrs(map[string]any{
"user.id": user.ID,
"user.username": user.Username,
})
}

ctxWithUserId := context.WithValue(r.Context(), log.UserIDKey, user.ID)
ctxWithUser := context.WithValue(ctxWithUserId, UserContextKey, user)
newRequest = r.WithContext(ctxWithUser)
Expand Down
47 changes: 47 additions & 0 deletions auth/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"

"github.com/platforma-dev/platforma/auth"
platformalog "github.com/platforma-dev/platforma/log"
)

func TestAuthenticationMiddleware_ValidSession(t *testing.T) {
Expand Down Expand Up @@ -36,6 +37,52 @@ func TestAuthenticationMiddleware_ValidSession(t *testing.T) {
}
}

func TestAuthenticationMiddleware_ValidSessionAddsUserInfoToWideEvent(t *testing.T) {
t.Parallel()

userSvc := &mockUserService{
users: map[string]*auth.User{
"valid-session-id": {ID: "user-id", Username: "testuser"},
},
cookieName: "session",
}
middleware := auth.NewAuthenticationMiddleware(userSvc)

handler := middleware.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))

req := httptest.NewRequest(http.MethodGet, "/", nil)
req.AddCookie(&http.Cookie{Name: "session", Value: "valid-session-id"})

event := platformalog.NewEvent("http.request")
req = req.WithContext(context.WithValue(req.Context(), platformalog.WideEventKey, event))

w := httptest.NewRecorder()

handler.ServeHTTP(w, req)

if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}

userID, ok := event.Attr("user.id")
if !ok {
t.Fatal("expected user.id attribute in event")
}
if userID != "user-id" {
t.Fatalf("expected user.id to be user-id, got %v", userID)
}

username, ok := event.Attr("user.username")
if !ok {
t.Fatal("expected user.username attribute in event")
}
if username != "testuser" {
t.Fatalf("expected user.username to be testuser, got %v", username)
}
}

func TestAuthenticationMiddleware_NoSessionCookie(t *testing.T) {
t.Parallel()

Expand Down
Loading