Skip to content
This repository has been archived by the owner on Sep 11, 2020. It is now read-only.

added credentials provider for basic auth #353

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions plumbing/transport/http/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -89,19 +92,34 @@ 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) {
if a == nil {
return
}

if len(a.username) < 1 || len(a.password) < 1 {
a.username, a.password = a.CredentialsProvider()
}

r.SetBasicAuth(a.username, a.password)
}

Expand Down
12 changes: 12 additions & 0 deletions plumbing/transport/http/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 "" }
Expand Down