Create context methods from admin database
This commit is contained in:
parent
48e2fabeb8
commit
623c296555
2 changed files with 30 additions and 1 deletions
|
@ -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 {
|
||||
|
|
8
ca/ca.go
8
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
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue