Dropping bsearch in BasicAuth()

This commit is contained in:
Manu Mtz-Almeida 2015-05-19 20:35:38 +02:00
parent bb98ec0490
commit f2ab821223
2 changed files with 11 additions and 19 deletions

22
auth.go
View File

@ -7,7 +7,6 @@ package gin
import ( import (
"crypto/subtle" "crypto/subtle"
"encoding/base64" "encoding/base64"
"sort"
"strconv" "strconv"
) )
@ -24,22 +23,17 @@ type (
authPairs []authPair authPairs []authPair
) )
func (a authPairs) Len() int { return len(a) } func (a authPairs) searchCredential(authValue string) (string, bool) {
func (a authPairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] } if len(authValue) == 0 {
func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }
func (a authPairs) searchCredential(auth string) (string, bool) {
if len(auth) == 0 {
return "", false return "", false
} }
// Search user in the slice of allowed credentials for _, pair := range a {
r := sort.Search(len(a), func(i int) bool { return a[i].Value >= auth }) if pair.Value == authValue {
if r < len(a) && secureCompare(a[r].Value, auth) { return pair.User, true
return a[r].User, true
} else {
return "", false
} }
} }
return "", false
}
// Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where // Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where
// the key is the user name and the value is the password, as well as the name of the Realm // the key is the user name and the value is the password, as well as the name of the Realm
@ -86,8 +80,6 @@ func processAccounts(accounts Accounts) authPairs {
User: user, User: user,
}) })
} }
// We have to sort the credentials in order to use bsearch later.
sort.Sort(pairs)
return pairs return pairs
} }

View File

@ -24,14 +24,14 @@ func TestBasicAuth(t *testing.T) {
User: "admin", User: "admin",
Value: "Basic YWRtaW46cGFzc3dvcmQ=", Value: "Basic YWRtaW46cGFzc3dvcmQ=",
}, },
authPair{
User: "bar",
Value: "Basic YmFyOmZvbw==",
},
authPair{ authPair{
User: "foo", User: "foo",
Value: "Basic Zm9vOmJhcg==", Value: "Basic Zm9vOmJhcg==",
}, },
authPair{
User: "bar",
Value: "Basic YmFyOmZvbw==",
},
} }
pairs := processAccounts(accounts) pairs := processAccounts(accounts)
assert.Equal(t, pairs, expectedPairs) assert.Equal(t, pairs, expectedPairs)