diff --git a/credential.go b/credential.go index ea9b32c..eb2d3db 100644 --- a/credential.go +++ b/credential.go @@ -1,25 +1,25 @@ package gitkit import ( - "fmt" "net/http" ) type Credential struct { - Username string - Password string + Username string + Password string + Authorization string } -func getCredential(req *http.Request) (Credential, error) { +func getCredential(req *http.Request) Credential { cred := Credential{} - user, pass, ok := req.BasicAuth() - if !ok { - return cred, fmt.Errorf("authentication failed") - } + user, pass, _ := req.BasicAuth() + + auth := req.Header.Get("Authorization") cred.Username = user cred.Password = pass + cred.Authorization = auth - return cred, nil + return cred } diff --git a/credential_test.go b/credential_test.go index 3c2d148..8544c56 100644 --- a/credential_test.go +++ b/credential_test.go @@ -9,15 +9,20 @@ import ( func Test_getCredential(t *testing.T) { req, _ := http.NewRequest("get", "http://localhost", nil) - _, err := getCredential(req) - assert.Error(t, err) - assert.Equal(t, "authentication failed", err.Error()) + cred := getCredential(req) + assert.Equal(t, cred.Authorization, "") req, _ = http.NewRequest("get", "http://localhost", nil) req.SetBasicAuth("Alladin", "OpenSesame") - cred, err := getCredential(req) + cred = getCredential(req) - assert.NoError(t, err) assert.Equal(t, "Alladin", cred.Username) assert.Equal(t, "OpenSesame", cred.Password) + assert.Contains(t, cred.Authorization, "Basic ") + + req, _ = http.NewRequest("get", "http://localhost", nil) + req.Header.Add("Authorization", "Bearer VerySecretToken") + cred = getCredential(req) + + assert.Equal(t, "Bearer VerySecretToken", cred.Authorization) } diff --git a/http.go b/http.go index 735b5e0..6a72e31 100644 --- a/http.go +++ b/http.go @@ -88,20 +88,14 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - authHeader := r.Header.Get("Authorization") - if authHeader == "" { + cred := getCredential(r) + if cred.Authorization == "" { + logError("auth", fmt.Errorf("no Authorization header found")) w.Header()["WWW-Authenticate"] = []string{`Basic realm=""`} w.WriteHeader(http.StatusUnauthorized) return } - cred, err := getCredential(r) - if err != nil { - logError("auth", err) - w.WriteHeader(http.StatusUnauthorized) - return - } - allow, err := s.AuthFunc(cred, req) if !allow || err != nil { if err != nil {