BasicAuth: simplify processing of the Accounts table

Use a map instead of an array to store authorization keys.
This commit is contained in:
Olivier Mengué 2015-11-13 15:04:23 +01:00
parent c1e660dd1a
commit 006a0cd4fc
2 changed files with 11 additions and 30 deletions

25
auth.go
View File

@ -14,21 +14,14 @@ const AuthUserKey = "user"
type (
Accounts map[string]string
authPair struct {
Value string
User string
}
authPairs []authPair
// "Basic "+base64(<user>:<password) => <user>
authPairs map[string]string
)
func (a authPairs) searchCredential(authValue string) (string, bool) {
if len(authValue) == 0 {
return "", false
}
for _, pair := range a {
if pair.Value == authValue {
return pair.User, true
}
if user, ok := a[authValue]; ok {
return user, true
}
return "", false
}
@ -68,16 +61,12 @@ func processAccounts(accounts Accounts) authPairs {
if len(accounts) == 0 {
panic("Empty list of authorized credentials")
}
pairs := make(authPairs, 0, len(accounts))
pairs := make(authPairs, len(accounts))
for user, password := range accounts {
if len(user) == 0 {
panic("User can not be empty")
}
value := authorizationHeader(user, password)
pairs = append(pairs, authPair{
Value: value,
User: user,
})
pairs[authorizationHeader(user, password)] = user
}
return pairs
}

View File

@ -20,18 +20,10 @@ func TestBasicAuth(t *testing.T) {
"bar": "foo",
})
assert.Len(t, pairs, 3)
assert.Contains(t, pairs, authPair{
User: "bar",
Value: "Basic YmFyOmZvbw==",
})
assert.Contains(t, pairs, authPair{
User: "foo",
Value: "Basic Zm9vOmJhcg==",
})
assert.Contains(t, pairs, authPair{
User: "admin",
Value: "Basic YWRtaW46cGFzc3dvcmQ=",
assert.Exactly(t, pairs, authPairs{
"Basic YmFyOmZvbw==": "bar",
"Basic Zm9vOmJhcg==": "foo",
"Basic YWRtaW46cGFzc3dvcmQ=": "admin",
})
}