From 15d8ac5f496468bafa035c11e3e9f9f6e0a9fdc9 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 | 13 +++++++++++++ pkg/modules/auth/auth_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 42 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 540e85d04..61a5f9b13 100644 --- a/pkg/modules/auth/auth.go +++ b/pkg/modules/auth/auth.go @@ -17,6 +17,7 @@ package auth import ( + "context" "fmt" "net/http" "net/url" @@ -26,6 +27,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" @@ -383,3 +385,14 @@ func RefreshSession(rawRefreshToken string) (*RefreshResult, error) { SessionID: session.ID, }, nil } + +// GetAuthFromContext retrieves the authenticated web.Auth from a plain +// context.Context, bridging Huma handlers to Vikunja's echo JWT flow. The +// humaecho5 adapter stashes the *echo.Context under EchoContextKey first. +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..b51b2da37 --- /dev/null +++ b/pkg/modules/auth/auth_test.go @@ -0,0 +1,29 @@ +// Vikunja is a to-do list application to facilitate your life. +// Copyright 2018-present Vikunja and contributors. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +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") +}