From 9628fa356224902ba9527a41d0ec99a627cd3344 Mon Sep 17 00:00:00 2001 From: Mariano Cano Date: Tue, 26 Apr 2022 12:54:54 -0700 Subject: [PATCH] Add methods to store and retrieve an authority from the context. --- authority/authority.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/authority/authority.go b/authority/authority.go index 9db38e14..091a01ae 100644 --- a/authority/authority.go +++ b/authority/authority.go @@ -7,6 +7,7 @@ import ( "crypto/x509" "encoding/hex" "log" + "net/http" "strings" "sync" "time" @@ -153,6 +154,27 @@ func NewEmbedded(opts ...Option) (*Authority, error) { return a, nil } +type authorityKey struct{} + +// NewContext adds the given authority to the context. +func NewContext(ctx context.Context, a *Authority) context.Context { + return context.WithValue(ctx, authorityKey{}, a) +} + +// FromContext returns the current authority from the given context. +func FromContext(ctx context.Context) (a *Authority, ok bool) { + a, ok = ctx.Value(authorityKey{}).(*Authority) + return +} + +// Middleware adds the current authority to the request context. +func (a *Authority) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := NewContext(r.Context(), a) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + // reloadAdminResources reloads admins and provisioners from the DB. func (a *Authority) reloadAdminResources(ctx context.Context) error { var (