-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.go
67 lines (58 loc) · 1.54 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"fmt"
"github.com/sdvcrx/cuttlefish/utils"
"net/http"
"strings"
)
type BasicAuth struct {
username string
password string
credentials string
credentialsBase64 string
}
func (auth BasicAuth) IsEmpty() bool {
return auth.username == "" && auth.password == ""
}
func (auth BasicAuth) Validate(authHeader string) bool {
if auth.IsEmpty() {
return true
}
credientials := strings.TrimPrefix(authHeader, "Basic ")
if credientials == auth.credentials || credientials == auth.credentialsBase64 {
return true
}
return false
}
func NewBasicAuth(username, password string) BasicAuth {
var proxyCredentials string
var proxyCredentialsBase64 string
if username != "" && password != "" {
proxyCredentials = fmt.Sprintf("%s:%s", username, password)
}
if proxyCredentials != "" {
proxyCredentialsBase64 = utils.Base64Encode(proxyCredentials)
}
return BasicAuth{
username,
password,
proxyCredentials,
proxyCredentialsBase64,
}
}
func ProxyAuthenticateHandler(handle http.HandlerFunc, authUser, authPassword string) http.Handler {
auth := NewBasicAuth(authUser, authPassword)
if auth.IsEmpty() {
return handle
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Need authorization
if !auth.Validate(r.Header.Get("Proxy-Authorization")) {
w.Header().Set("Proxy-Authenticate", "Basic realm=\"Password\"")
http.Error(w, "", http.StatusProxyAuthRequired)
logger.Error().Msgf("Accessing proxy deny, password is wrong or empty")
return
}
handle(w, r)
})
}