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

View File

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