From abc0cdfc6a4817e1312619dfab5bb7ea303223bb Mon Sep 17 00:00:00 2001 From: kolaente Date: Mon, 20 Apr 2026 10:43:15 +0200 Subject: [PATCH] feat(auth): add GetAuthFromContext for Huma handlers --- pkg/modules/auth/auth.go | 15 +++++++++++++++ pkg/modules/auth/auth_test.go | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 pkg/modules/auth/auth_test.go diff --git a/pkg/modules/auth/auth.go b/pkg/modules/auth/auth.go index 4e2ebb94e..a3d6bc76a 100644 --- a/pkg/modules/auth/auth.go +++ b/pkg/modules/auth/auth.go @@ -17,6 +17,7 @@ package auth import ( + "context" "fmt" "net/http" "strings" @@ -25,6 +26,7 @@ import ( "code.vikunja.io/api/pkg/config" "code.vikunja.io/api/pkg/db" "code.vikunja.io/api/pkg/models" + "code.vikunja.io/api/pkg/modules/humaecho5" "code.vikunja.io/api/pkg/user" "code.vikunja.io/api/pkg/web" @@ -366,3 +368,16 @@ func RefreshSession(rawRefreshToken string) (*RefreshResult, error) { SessionID: session.ID, }, nil } + +// GetAuthFromContext retrieves the authenticated web.Auth from a Go +// context.Context. This bridges Huma handlers (which receive a plain +// context.Context) to Vikunja's echo-based JWT flow. The humaecho5 +// adapter stashes the underlying *echo.Context under +// humaecho5.EchoContextKey before invoking the Huma handler. +func GetAuthFromContext(ctx context.Context) (web.Auth, error) { + ec, ok := ctx.Value(humaecho5.EchoContextKey).(*echo.Context) + if !ok { + return nil, fmt.Errorf("no echo.Context on request context; are you calling GetAuthFromContext from a Huma handler dispatched by humaecho5?") + } + return GetAuthFromClaims(ec) +} diff --git a/pkg/modules/auth/auth_test.go b/pkg/modules/auth/auth_test.go new file mode 100644 index 000000000..1ce6f1170 --- /dev/null +++ b/pkg/modules/auth/auth_test.go @@ -0,0 +1,18 @@ +package auth + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestGetAuthFromContext_NoEchoContext(t *testing.T) { + _, err := GetAuthFromContext(context.Background()) + assert.Error(t, err, "should fail when echo.Context isn't stashed on ctx") +} + +// NOTE: A full positive test requires a valid JWT and DB fixtures. +// That path is exercised by the Label integration test in Phase E. +// Here we only prove the helper returns an error (not a panic) on an +// unwrapped context.