Refactor auth to load token outside wrappers

This commit is contained in:
Ben Toogood
2020-05-14 11:06:22 +01:00
parent 0955671e45
commit 5764519f5b
7 changed files with 91 additions and 192 deletions

View File

@@ -12,7 +12,6 @@ import (
"github.com/micro/go-micro/v2/errors"
"github.com/micro/go-micro/v2/metadata"
"github.com/micro/go-micro/v2/server"
"github.com/micro/go-micro/v2/util/config"
)
type fromServiceWrapper struct {
@@ -159,50 +158,13 @@ func (a *authWrapper) Call(ctx context.Context, req client.Request, rsp interfac
return a.Client.Call(ctx, req, rsp, opts...)
}
// performs the call with the authorization token provided
callWithToken := func(token string) error {
ctx := metadata.Set(ctx, "Authorization", auth.BearerScheme+token)
return a.Client.Call(ctx, req, rsp, opts...)
}
// check to see if we have a valid access token
aaOpts := aa.Options()
if aaOpts.Token != nil && aaOpts.Token.Expiry.Unix() > time.Now().Unix() {
return callWithToken(aaOpts.Token.AccessToken)
}
// check to ensure we're not calling auth, since this will result in
// an endless loop
if req.Service() == "go.micro.auth" {
ctx = metadata.Set(ctx, "Authorization", auth.BearerScheme+aaOpts.Token.AccessToken)
return a.Client.Call(ctx, req, rsp, opts...)
}
// if we have a refresh token we can use this to generate another access token
if aaOpts.Token != nil {
tok, err := aa.Token(auth.WithToken(aaOpts.Token.RefreshToken))
if err != nil {
return err
}
aa.Init(auth.ClientToken(tok))
return callWithToken(tok.AccessToken)
}
// generate a new token if we have credentials
if len(aaOpts.ID) > 0 && len(aaOpts.Secret) > 0 {
tok, err := aa.Token(auth.WithCredentials(aaOpts.ID, aaOpts.Secret))
if err != nil {
return err
}
aa.Init(auth.ClientToken(tok))
return callWithToken(tok.AccessToken)
}
// check to see if a token was provided in config, this is normally used for
// setting the token when calling via the cli
if token, err := config.Get("micro", "auth", "token"); err == nil && len(token) > 0 {
return callWithToken(token)
}
// call without an auth token
return a.Client.Call(ctx, req, rsp, opts...)
}