From 71b27871dc308a586f286d1454acb0fafea91a90 Mon Sep 17 00:00:00 2001 From: Drew DeVault Date: Wed, 8 Jul 2026 11:16:56 +0200 Subject: [PATCH] auth: add function to create ad-hoc authenticated contexts --- auth/middleware.go | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/auth/middleware.go b/auth/middleware.go index 98416ac6a3f02e2ab247eadd96d3923cdee62f4a..dde1b7cef600fff4815103ac21293badded695cd 100644 --- a/auth/middleware.go +++ b/auth/middleware.go @@ -219,8 +219,7 @@ func cookieAuth(cookie *http.Cookie, w http.ResponseWriter, auth.AuthMethod = AUTH_COOKIE - ctx := context.WithValue(r.Context(), userCtxKey, auth) - r = r.WithContext(ctx) + r = r.WithContext(Context(r.Context(), auth)) next.ServeHTTP(w, r) } @@ -310,8 +309,7 @@ func internalAuth(payload []byte, w http.ResponseWriter, r *http.Request, next h break } - ctx := context.WithValue(r.Context(), userCtxKey, auth) - r = r.WithContext(ctx) + r = r.WithContext(Context(r.Context(), auth)) next.ServeHTTP(w, r) } @@ -558,8 +556,7 @@ func OAuth2(token string, hash [64]byte, w http.ResponseWriter, panic(err) // unreachable } - ctx := context.WithValue(r.Context(), userCtxKey, &auth) - r = r.WithContext(ctx) + r = r.WithContext(Context(r.Context(), &auth)) next.ServeHTTP(w, r) } @@ -592,7 +589,7 @@ func WebhookAuth(ctx context.Context, auth *AuthContext, whAuth.BearerToken.ClientID = *clientID } - return context.WithValue(ctx, userCtxKey, &whAuth), nil + return Context(ctx, auth), nil } func Middleware(conf ini.File, apiconf string) func(http.Handler) http.Handler { @@ -641,6 +638,7 @@ func Middleware(conf ini.File, apiconf string) func(http.Handler) http.Handler { } } +// Returns the authentication details associated with this context. func ForContext(ctx context.Context) *AuthContext { raw, ok := ctx.Value(userCtxKey).(*AuthContext) if !ok { @@ -648,3 +646,8 @@ func ForContext(ctx context.Context) *AuthContext { } return raw } + +// Creates a new authenticated context. +func Context(base context.Context, auth *AuthContext) context.Context { + return context.WithValue(base, userCtxKey, auth) +}