Inject Namespace into Context

This commit is contained in:
Ben Toogood 2020-04-14 09:14:07 +01:00
parent bf65dc71c7
commit d61d30ef66
5 changed files with 29 additions and 5 deletions

View File

@ -133,3 +133,11 @@ func ContextWithAccount(ctx context.Context, account *Account) (context.Context,
// generate a new context with the MetadataKey set
return metadata.Set(ctx, MetadataKey, string(bytes)), nil
}
// NamespaceFromContext gets the namespace from the context
func NamespaceFromContext(ctx context.Context) string {
if ns, ok := metadata.Get(ctx, NamespaceKey); ok {
return ns
}
return DefaultNamespace
}

View File

@ -9,7 +9,7 @@ var (
)
func NewAuth(opts ...Option) Auth {
return &noop{}
return &noop{opts: NewOptions(opts...)}
}
type noop struct {

View File

@ -7,6 +7,19 @@ import (
"github.com/micro/go-micro/v2/store"
)
func NewOptions(opts ...Option) Options {
var options Options
for _, o := range opts {
o(&options)
}
if len(options.Namespace) == 0 {
options.Namespace = DefaultNamespace
}
return options
}
type Options struct {
// Namespace the service belongs to
Namespace string

View File

@ -18,9 +18,7 @@ import (
// NewAuth returns a new instance of the Auth service
func NewAuth(opts ...auth.Option) auth.Auth {
svc := new(svc)
svc.Init(opts...)
return svc
return &svc{options: auth.NewOptions(opts...)}
}
// svc is the service implementation of the Auth interface

View File

@ -159,7 +159,7 @@ func AuthHandler(fn func() auth.Auth) server.HandlerWrapper {
// Inspect the token and get the account
account, err := a.Inspect(token)
if err != nil {
account = &auth.Account{}
account = &auth.Account{Namespace: a.Options().Namespace}
}
// construct the resource
@ -183,6 +183,11 @@ func AuthHandler(fn func() auth.Auth) server.HandlerWrapper {
return err
}
// Set the namespace in the context
if _, ok := metadata.Get(ctx, auth.NamespaceKey); !ok {
ctx = metadata.Set(ctx, auth.NamespaceKey, a.Options().Namespace)
}
// The user is authorised, allow the call
return h(ctx, req, rsp)
}