-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.go
More file actions
84 lines (66 loc) · 1.83 KB
/
basic.go
File metadata and controls
84 lines (66 loc) · 1.83 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package security
import (
"encoding/base64"
"fmt"
"net/http"
"net/url"
"github.com/hasura/ndc-http/ndc-http-schema/schema"
)
// BasicCredential represents the basic authentication credential.
type BasicCredential struct {
UserInfo *url.Userinfo
Header string
client *http.Client
}
var _ Credential = &BasicCredential{}
// NewBasicCredential creates a new BasicCredential instance.
func NewBasicCredential(
client *http.Client,
config *schema.BasicAuthConfig,
) (*BasicCredential, error) {
user, err := config.Username.Get()
if err != nil {
return nil, fmt.Errorf("BasicAuthConfig.Username: %w", err)
}
password, err := config.Password.Get()
if err != nil {
return nil, fmt.Errorf("BasicAuthConfig.Password: %w", err)
}
result := &BasicCredential{
client: client,
}
if password != "" {
result.UserInfo = url.UserPassword(user, password)
} else {
result.UserInfo = url.User(user)
}
return result, nil
}
// GetClient gets the HTTP client that is compatible with the current credential.
func (bc BasicCredential) GetClient() *http.Client {
return bc.client
}
// Inject the credential into the incoming request.
func (bc BasicCredential) Inject(req *http.Request) (bool, error) {
if bc.UserInfo == nil {
return false, nil
}
return bc.inject(req, *bc.UserInfo)
}
// InjectMock injects the mock credential into the incoming request for explain APIs.
func (bc BasicCredential) InjectMock(req *http.Request) bool {
if bc.UserInfo == nil {
return false
}
_, _ = bc.inject(req, *url.UserPassword("xxx", "xxx"))
return true
}
func (bc BasicCredential) inject(req *http.Request, userInfo url.Userinfo) (bool, error) {
if bc.Header != "" {
b64Value := base64.StdEncoding.EncodeToString([]byte(userInfo.String()))
req.Header.Set(bc.Header, "Basic "+b64Value)
} else {
req.URL.User = &userInfo
}
return true, nil
}