Add methods to store and retrieve an authority from the context.

This commit is contained in:
Mariano Cano 2022-04-26 12:54:54 -07:00
parent 3424442c50
commit 9628fa3562

View file

@ -7,6 +7,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/hex" "encoding/hex"
"log" "log"
"net/http"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -153,6 +154,27 @@ func NewEmbedded(opts ...Option) (*Authority, error) {
return a, nil 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. // reloadAdminResources reloads admins and provisioners from the DB.
func (a *Authority) reloadAdminResources(ctx context.Context) error { func (a *Authority) reloadAdminResources(ctx context.Context) error {
var ( var (