mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-15 21:06:39 +08:00
BasicAuth: simplify processing of the Accounts table
Use a map instead of an array to store authorization keys.
This commit is contained in:
parent
c1e660dd1a
commit
006a0cd4fc
25
auth.go
25
auth.go
@ -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
|
||||
}
|
||||
|
16
auth_test.go
16
auth_test.go
@ -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",
|
||||
})
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user