Refactores BasicAuth

This commit is contained in:
Manu Mtz-Almeida 2015-03-23 04:38:32 +01:00
parent 5857ddcd2c
commit 4103061a4a
2 changed files with 7 additions and 10 deletions

13
auth.go
View File

@ -33,10 +33,7 @@ func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }
// the key is the user name and the value is the password, as well as the name of the Realm
// (see http://tools.ietf.org/html/rfc2617#section-1.2)
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
pairs, err := processAccounts(accounts)
if err != nil {
panic(err)
}
pairs := processAccounts(accounts)
return func(c *Context) {
// Search user in the slice of allowed credentials
user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))
@ -61,14 +58,14 @@ func BasicAuth(accounts Accounts) HandlerFunc {
return BasicAuthForRealm(accounts, "")
}
func processAccounts(accounts Accounts) (authPairs, error) {
func processAccounts(accounts Accounts) authPairs {
if len(accounts) == 0 {
return nil, errors.New("Empty list of authorized credentials")
panic("Empty list of authorized credentials")
}
pairs := make(authPairs, 0, len(accounts))
for user, password := range accounts {
if len(user) == 0 {
return nil, errors.New("User can not be empty")
panic("User can not be empty")
}
base := user + ":" + password
value := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
@ -79,7 +76,7 @@ func processAccounts(accounts Accounts) (authPairs, error) {
}
// We have to sort the credentials in order to use bsearch later.
sort.Sort(pairs)
return pairs, nil
return pairs
}
func searchCredential(pairs authPairs, auth string) (string, bool) {

View File

@ -27,7 +27,7 @@ func TestBasicAuthSucceed(t *testing.T) {
r.ServeHTTP(w, req)
if w.Code != 200 {
t.Errorf("Response code should be Ok, was: %s", w.Code)
t.Errorf("Response code should be Ok, was: %d", w.Code)
}
bodyAsString := w.Body.String()
@ -52,7 +52,7 @@ func TestBasicAuth401(t *testing.T) {
r.ServeHTTP(w, req)
if w.Code != 401 {
t.Errorf("Response code should be Not autorized, was: %s", w.Code)
t.Errorf("Response code should be Not autorized, was: %d", w.Code)
}
if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {