feat(auth): add GetAuthFromContext for Huma handlers

This commit is contained in:
kolaente
2026-04-20 10:43:15 +02:00
parent 1d6c1cf838
commit abc0cdfc6a
2 changed files with 33 additions and 0 deletions

View File

@@ -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)
}

View File

@@ -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.