mirror of
https://github.com/etcd-io/etcd.git
synced 2024-09-27 06:25:44 +00:00
netutil: add BasicAuth function
etcd ships it's own BasicAuth function and no longer requires Go 1.4 to build.
This commit is contained in:
@@ -15,10 +15,13 @@
|
||||
package netutil
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -99,3 +102,36 @@ func URLStringsEqual(a []string, b []string) bool {
|
||||
|
||||
return URLsEqual(urlsA, urlsB)
|
||||
}
|
||||
|
||||
// BasicAuth returns the username and password provided in the request's
|
||||
// Authorization header, if the request uses HTTP Basic Authentication.
|
||||
// See RFC 2617, Section 2.
|
||||
// Based on the BasicAuth method from the Golang standard lib.
|
||||
// TODO: use the standard lib BasicAuth method when we move to Go 1.4.
|
||||
func BasicAuth(r *http.Request) (username, password string, ok bool) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth == "" {
|
||||
return
|
||||
}
|
||||
return parseBasicAuth(auth)
|
||||
}
|
||||
|
||||
// parseBasicAuth parses an HTTP Basic Authentication string.
|
||||
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
|
||||
// Taken from the Golang standard lib.
|
||||
// TODO: use the standard lib BasicAuth method when we move to Go 1.4.
|
||||
func parseBasicAuth(auth string) (username, password string, ok bool) {
|
||||
if !strings.HasPrefix(auth, "Basic ") {
|
||||
return
|
||||
}
|
||||
c, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(auth, "Basic "))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cs := string(c)
|
||||
s := strings.IndexByte(cs, ':')
|
||||
if s < 0 {
|
||||
return
|
||||
}
|
||||
return cs[:s], cs[s+1:], true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user