Skip to content

Commit

Permalink
authn
Browse files Browse the repository at this point in the history
  • Loading branch information
bmoylan committed Aug 17, 2023
1 parent 5a2bdbd commit 244b8db
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 25 deletions.
26 changes: 4 additions & 22 deletions conjure-go-client/httpclient/authn.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,38 +61,20 @@ func newAuthTokenMiddlewareFromRefreshable(token refreshable.Refreshable[*string
}
}

// BasicAuthProvider accepts a context and returns either:
//
// (1) a nonempty BasicAuth and a nil error, or
//
// (2) an empty BasicAuth and a non-nil error.
type BasicAuthProvider func(context.Context) (BasicAuth, error)

// basicAuthMiddleware wraps a refreshing BasicAuth pointer and injects basic auth credentials if the pointer is not nil
type basicAuthMiddleware struct {
provider BasicAuthProvider
refreshable.Refreshable[*refreshingclient.BasicAuth]
}

func (b *basicAuthMiddleware) RoundTrip(req *http.Request, next http.RoundTripper) (*http.Response, error) {
basicAuth, err := b.provider(req.Context())
if err != nil {
return nil, err
if basicAuth := b.Current(); basicAuth != nil {
setBasicAuth(req.Header, basicAuth.User, basicAuth.Password)
}
setBasicAuth(req.Header, basicAuth.User, basicAuth.Password)
return next.RoundTrip(req)
}

func newBasicAuthMiddlewareFromRefreshable(auth refreshable.Refreshable[*refreshingclient.BasicAuth]) Middleware {
disabled, _ := refreshable.Map(auth, func(a *refreshingclient.BasicAuth) bool { return a == nil })
return &conditionalMiddleware{
Disabled: disabled,
Delegate: &basicAuthMiddleware{provider: func(ctx context.Context) (BasicAuth, error) {
if b := auth.Current(); b != nil {
return BasicAuth{User: b.User, Password: b.Password}, nil
}
return BasicAuth{}, nil
}},
}
return &basicAuthMiddleware{Refreshable: auth}
}

func setBasicAuth(h http.Header, username, password string) {
Expand Down
9 changes: 6 additions & 3 deletions conjure-go-client/httpclient/client_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -534,9 +534,12 @@ func WithErrorDecoder(errorDecoder ErrorDecoder) ClientParam {
// WithBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and
// password.
func WithBasicAuth(user, password string) ClientParam {
return WithMiddleware(&basicAuthMiddleware{provider: func(ctx context.Context) (BasicAuth, error) {
return BasicAuth{User: user, Password: password}, nil
}})
return WithMiddleware(&basicAuthMiddleware{
Refreshable: refreshable.New(&refreshingclient.BasicAuth{
User: user,
Password: password,
}),
})
}

// WithBalancedURIScoring adds middleware that prioritizes sending requests to URIs with the fewest in-flight requests
Expand Down

0 comments on commit 244b8db

Please sign in to comment.