Ver Fonte

Create context methods from admin database

Mariano Cano há 4 anos atrás
pai
commit
623c296555
2 ficheiros alterados com 30 adições e 1 exclusões
  1. 23 0
      authority/admin/db.go
  2. 7 1
      ca/ca.go

+ 23 - 0
authority/admin/db.go

@@ -71,6 +71,29 @@ type DB interface {
 	DeleteAdmin(ctx context.Context, id string) error
 }
 
+type dbKey struct{}
+
+// NewContext adds the given admin database to the context.
+func NewContext(ctx context.Context, db DB) context.Context {
+	return context.WithValue(ctx, dbKey{}, db)
+}
+
+// FromContext returns the current admin database from the given context.
+func FromContext(ctx context.Context) (db DB, ok bool) {
+	db, ok = ctx.Value(dbKey{}).(DB)
+	return
+}
+
+// MustFromContext returns the current admin database from the given context. It
+// will panic if it's not in the context.
+func MustFromContext(ctx context.Context) DB {
+	if db, ok := FromContext(ctx); !ok {
+		panic("admin database is not in the context")
+	} else {
+		return db
+	}
+}
+
 // MockDB is an implementation of the DB interface that should only be used as
 // a mock in tests.
 type MockDB struct {

+ 7 - 1
ca/ca.go

@@ -20,6 +20,7 @@ import (
 	acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
 	"github.com/smallstep/certificates/api"
 	"github.com/smallstep/certificates/authority"
+	"github.com/smallstep/certificates/authority/admin"
 	adminAPI "github.com/smallstep/certificates/authority/admin/api"
 	"github.com/smallstep/certificates/authority/config"
 	"github.com/smallstep/certificates/db"
@@ -280,7 +281,7 @@ func (ca *CA) Init(cfg *config.Config) (*CA, error) {
 		insecureHandler = logger.Middleware(insecureHandler)
 	}
 
-	// Add authority handler
+	// Create context with all the necessary values.
 	baseContext := buildContext(auth)
 
 	ca.srv = server.New(cfg.Address, handler, tlsConfig)
@@ -304,9 +305,14 @@ func (ca *CA) Init(cfg *config.Config) (*CA, error) {
 	return ca, nil
 }
 
+// buildContext builds the server base context.
 func buildContext(a *authority.Authority) context.Context {
 	ctx := authority.NewContext(context.Background(), a)
 
+	if db := a.GetAdminDatabase(); db != nil {
+		ctx = admin.NewContext(ctx, db)
+	}
+
 	return ctx
 }