forked from DependencyTrack/client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
84 lines (67 loc) · 1.78 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package dtrack
import (
"context"
"fmt"
"net/http"
)
func WithAPIKey(apiKey string) ClientOption {
return func(c *Client) error {
if apiKey == "" {
return fmt.Errorf("no api key provided")
}
currentTransport := c.httpClient.Transport
if currentTransport == nil {
currentTransport = http.DefaultTransport
}
c.httpClient.Transport = &authHeaderTransport{
name: "X-Api-Key",
value: apiKey,
transport: currentTransport,
}
return nil
}
}
func WithBearerToken(token string) ClientOption {
return func(c *Client) error {
if token == "" {
return fmt.Errorf("no token provided")
}
currentTransport := c.httpClient.Transport
if currentTransport == nil {
currentTransport = http.DefaultTransport
}
c.httpClient.Transport = &authHeaderTransport{
name: "Authorization",
value: fmt.Sprintf("Bearer %s", token),
transport: currentTransport,
}
return nil
}
}
const contextKeyNoAuth contextKey = "noauth"
func withoutAuth() requestOption {
return func(r *http.Request) error {
ctx := context.WithValue(r.Context(), contextKeyNoAuth, true)
*r = *(r.WithContext(ctx))
return nil
}
}
type authHeaderTransport struct {
name string
value string
transport http.RoundTripper
}
func (t authHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) {
unauthenticated, ok := req.Context().Value(contextKeyNoAuth).(bool)
if ok && unauthenticated {
return t.transport.RoundTrip(req)
}
reqCopy := *req // Shallow copy of req
// Deep copy of request headers, because we'll modify them
reqCopy.Header = make(http.Header, len(req.Header))
for hn, hv := range req.Header {
reqCopy.Header[hn] = append([]string(nil), hv...)
}
reqCopy.Header.Set(t.name, t.value)
return t.transport.RoundTrip(&reqCopy)
}