Performance improvement in Auth middleware

This commit is contained in:
Manu Mtz-Almeida 2015-04-07 20:00:10 +02:00
parent a4eadceb45
commit af4980ece2
1 changed files with 5 additions and 4 deletions

View File

@ -34,16 +34,17 @@ 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 // 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) // (see http://tools.ietf.org/html/rfc2617#section-1.2)
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
if realm == "" {
realm = "Authorization Required"
}
realm = fmt.Sprintf("Basic realm=\"%s\"", realm)
pairs := processAccounts(accounts) pairs := processAccounts(accounts)
return func(c *Context) { return func(c *Context) {
// Search user in the slice of allowed credentials // Search user in the slice of allowed credentials
user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization")) user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))
if !ok { if !ok {
// Credentials doesn't match, we return 401 Unauthorized and abort request. // Credentials doesn't match, we return 401 Unauthorized and abort request.
if realm == "" { c.Writer.Header().Set("WWW-Authenticate", realm)
realm = "Authorization Required"
}
c.Writer.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", realm))
c.Fail(401, errors.New("Unauthorized")) c.Fail(401, errors.New("Unauthorized"))
} else { } else {
// user is allowed, set UserId to key "user" in this context, the userId can be read later using // user is allowed, set UserId to key "user" in this context, the userId can be read later using