-
Notifications
You must be signed in to change notification settings - Fork 2
/
httpclient_auth_transport.go
68 lines (54 loc) · 1.5 KB
/
httpclient_auth_transport.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
package client
import (
"fmt"
"net/http"
"github.com/pkg/errors"
"github.com/dpb587/ssoca/client/service"
globalservice "github.com/dpb587/ssoca/service"
)
const AuthorizationNone = "none"
type AuthTransport struct {
Runtime Runtime
Base http.RoundTripper
serviceManager service.Manager
}
func NewAuthTransport(runtime Runtime, serviceManager service.Manager, base http.RoundTripper) http.RoundTripper {
return &AuthTransport{
Runtime: runtime,
Base: base,
serviceManager: serviceManager,
}
}
func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.Header.Get("Authorization") == AuthorizationNone {
// do nothing
req.Header.Del("Authorization")
} else {
env, err := t.Runtime.GetEnvironment()
if err != nil {
return nil, errors.Wrap(err, "retrieving environment")
}
if env.Auth != nil {
authServiceType := globalservice.Type(env.Auth.Type)
svc, err := t.serviceManager.Get(authServiceType, env.Auth.Name)
if err != nil {
return nil, errors.Wrap(err, "getting authentication service")
}
authService, ok := svc.(service.AuthService)
if !ok {
return nil, fmt.Errorf("cannot authenticate with service: %s", authServiceType)
}
err = authService.AuthRequest(req)
if err != nil {
return nil, errors.Wrap(err, "authenticating request")
}
}
}
return t.base().RoundTrip(req)
}
func (t *AuthTransport) base() http.RoundTripper {
if t.Base != nil {
return t.Base
}
return http.DefaultTransport
}