Skip to content
Merged
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
18 changes: 9 additions & 9 deletions credential.go
Original file line number Diff line number Diff line change
@@ -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
}
15 changes: 10 additions & 5 deletions credential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
12 changes: 3 additions & 9 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down