2010-11-15 03:52:52 +00:00
|
|
|
package auth
|
2010-07-26 03:34:04 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
"http"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var kBasicAuthPattern *regexp.Regexp = regexp.MustCompile(`^Basic ([a-zA-Z0-9\+/=]+)`)
|
|
|
|
|
2010-11-15 03:52:52 +00:00
|
|
|
var AccessPassword string
|
2010-07-26 03:34:04 +00:00
|
|
|
|
2010-11-15 03:52:52 +00:00
|
|
|
func IsAuthorized(req *http.Request) bool {
|
2010-07-26 03:34:04 +00:00
|
|
|
auth, present := req.Header["Authorization"]
|
|
|
|
if !present {
|
|
|
|
return false
|
|
|
|
}
|
2010-09-08 05:02:20 +00:00
|
|
|
matches := kBasicAuthPattern.FindStringSubmatch(auth)
|
2010-07-26 03:34:04 +00:00
|
|
|
if len(matches) != 2 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
encoded := matches[1]
|
|
|
|
enc := base64.StdEncoding
|
|
|
|
decBuf := make([]byte, enc.DecodedLen(len(encoded)))
|
|
|
|
n, err := enc.Decode(decBuf, []byte(encoded))
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
userpass := strings.Split(string(decBuf[0:n]), ":", 2)
|
|
|
|
if len(userpass) != 2 {
|
|
|
|
fmt.Println("didn't get two pieces")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
password := userpass[1] // username at index 0 is currently unused
|
2010-11-15 03:52:52 +00:00
|
|
|
return password != "" && password == AccessPassword
|
2010-07-26 03:34:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// requireAuth wraps a function with another function that enforces
|
|
|
|
// HTTP Basic Auth.
|
2010-11-15 03:52:52 +00:00
|
|
|
func RequireAuth(handler func(conn http.ResponseWriter, req *http.Request)) func (conn http.ResponseWriter, req *http.Request) {
|
2010-10-04 15:28:14 +00:00
|
|
|
return func (conn http.ResponseWriter, req *http.Request) {
|
2010-11-15 03:52:52 +00:00
|
|
|
if !IsAuthorized(req) {
|
2010-11-29 03:56:57 +00:00
|
|
|
req.Body.Close() // http://code.google.com/p/go/issues/detail?id=1306
|
2010-07-26 03:34:04 +00:00
|
|
|
conn.SetHeader("WWW-Authenticate", "Basic realm=\"camlistored\"")
|
|
|
|
conn.WriteHeader(http.StatusUnauthorized)
|
|
|
|
fmt.Fprintf(conn, "Authentication required.\n")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
handler(conn, req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|