Files
httptunnel/multiproxy/authenticate.go

80 lines
1.8 KiB
Go
Raw Normal View History

2019-07-09 02:08:35 -04:00
package i2pbrowserproxy
import (
"bytes"
"encoding/base64"
2019-07-09 02:08:35 -04:00
"io/ioutil"
"log"
"net/http"
"strings"
2019-07-09 02:08:35 -04:00
)
// Create a struct that models the structure of a user, both in the request body, and in the DB
type Credentials struct {
User string
Site string
2019-07-09 02:08:35 -04:00
}
func ProxyBasicAuth(r *http.Request) (username, password string, ok bool) {
auth := r.Header.Get("Proxy-Authorization")
if auth == "" {
return
2019-07-09 02:08:35 -04:00
}
return parseBasicAuth(auth)
2019-07-09 02:08:35 -04:00
}
func parseBasicAuth(auth string) (username, password string, ok bool) {
const prefix = "Basic "
// Case insensitive prefix match. See Issue 22736.
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
2019-07-09 02:08:35 -04:00
}
2019-07-09 02:08:35 -04:00
func DecodeIdentity(body *http.Request) (*http.Request, *Credentials, error) {
var creds Credentials
bb, err := ioutil.ReadAll(body.Body)
if err != nil {
return body, &creds, err
2019-07-09 02:08:35 -04:00
}
req, err := http.NewRequest(body.Method, body.URL.String(), bytes.NewReader(bb))
if err != nil {
return req, &creds, err
2019-07-09 02:08:35 -04:00
}
var ok bool
creds.User, creds.Site, ok = ProxyBasicAuth(body)
if ok {
log.Println("OK", creds.User, creds.Site)
} else {
log.Println("NOT OK", creds.User, creds.Site)
2019-07-09 02:08:35 -04:00
}
return req, &creds, nil
}
func (m *SAMMultiProxy) Signin(w http.ResponseWriter, r *http.Request) (*samClient, *http.Request) {
if m.aggressive {
return m.findClient(r.Host), r
}
r, creds, err := DecodeIdentity(r)
if err != nil {
if err.Error() == "EOF" {
log.Println("No auth parameters passed, falling back to general")
return m.clients["general"], r
}
w.WriteHeader(http.StatusBadRequest)
return nil, nil
}
return m.findClient(creds.Site), r
}