diff --git a/plumbing/transport/http/common.go b/plumbing/transport/http/common.go index 930e8eb91..cb90ca663 100644 --- a/plumbing/transport/http/common.go +++ b/plumbing/transport/http/common.go @@ -66,6 +66,9 @@ func (s *session) applyAuthToRequest(req *http.Request) { s.auth.setAuth(req) } +// CredentialsProvider is a function that returns a username and password +type CredentialsProvider func() (string, string) + // AuthMethod is concrete implementation of common.AuthMethod for HTTP services type AuthMethod interface { transport.AuthMethod @@ -89,12 +92,23 @@ func basicAuthFromEndpoint(ep transport.Endpoint) *BasicAuth { // BasicAuth represent a HTTP basic auth type BasicAuth struct { - username, password string + CredentialsProvider CredentialsProvider + username, password string } // NewBasicAuth returns a basicAuth base on the given user and password func NewBasicAuth(username, password string) *BasicAuth { - return &BasicAuth{username, password} + ba := &BasicAuth{ + username: username, + password: password, + } + + ba.CredentialsProvider = ba.defaultCredentialsProvider + return ba +} + +func (a *BasicAuth) defaultCredentialsProvider() (string, string) { + return a.username, a.password } func (a *BasicAuth) setAuth(r *http.Request) { @@ -102,6 +116,10 @@ func (a *BasicAuth) setAuth(r *http.Request) { return } + if len(a.username) < 1 || len(a.password) < 1 { + a.username, a.password = a.CredentialsProvider() + } + r.SetBasicAuth(a.username, a.password) } diff --git a/plumbing/transport/http/common_test.go b/plumbing/transport/http/common_test.go index d1f36d3e1..6a21c1ce3 100644 --- a/plumbing/transport/http/common_test.go +++ b/plumbing/transport/http/common_test.go @@ -86,6 +86,18 @@ func (s *ClientSuite) TestSetAuth(c *C) { c.Assert(auth, Equals, r.(*upSession).auth) } +func (s *ClientSuite) TestCredentialsProvider(c *C) { + auth := &BasicAuth{} + auth.CredentialsProvider = func() (string, string) { return "foo", "b4r" } + req, _ := http.NewRequest("GET", "foo", nil) + auth.setAuth(req) + u, p, ok := req.BasicAuth() + + c.Assert(u, Equals, "foo") + c.Assert(p, Equals, "b4r") + c.Assert(ok, Equals, true) +} + type mockAuth struct{} func (*mockAuth) Name() string { return "" }