forked from kevholditch/go-form3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticated_client.go
208 lines (167 loc) · 6.07 KB
/
authenticated_client.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package form3
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"github.com/ewilde/go-form3/client"
"github.com/go-openapi/runtime"
rc "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/hashicorp/terraform/helper/logging"
)
type AuthenticatedClient struct {
AccessToken string
SecurityClient *client.Form3CorelibDataStructures
NotificationClient *client.Form3CorelibDataStructures
Config *client.TransportConfig
HttpClient *http.Client
OrganisationId string
OrganisationClient *client.Form3CorelibDataStructures
AssociationClient *client.Form3CorelibDataStructures
AccountClient *client.Form3CorelibDataStructures
LimitsClient *client.Form3CorelibDataStructures
PaymentdefaultsClient *client.Form3CorelibDataStructures
TransactionClient *client.Form3CorelibDataStructures
}
type AuthenticatedClientCheckRedirect struct {
}
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
func (r *AuthenticatedClientCheckRedirect) CheckRedirect(req *http.Request, via []*http.Request) error {
req.Header.Add("Authorization", via[0].Header.Get("Authorization"))
return nil
}
func NewAuthenticatedClient(config *client.TransportConfig) *AuthenticatedClient {
a := &AuthenticatedClientCheckRedirect{}
var authClient *AuthenticatedClient
h := &http.Client{
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if len(authClient.AccessToken) > 0 {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authClient.AccessToken))
}
if logging.IsDebugOrHigher() {
dump, errDump := httputil.DumpRequestOut(req, true)
if errDump != nil {
log.Fatal(errDump)
}
log.Printf("[DEBUG] %s %s", req.URL.String(), string(dump))
}
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
return nil, err
}
if logging.IsDebugOrHigher() {
dump, errDump := httputil.DumpResponse(resp, true)
if errDump != nil {
log.Fatal(errDump)
}
log.Printf("[DEBUG] %s %s", req.URL.String(), string(dump))
}
return resp, err
}),
CheckRedirect: a.CheckRedirect,
}
config.WithBasePath("/v1/security")
rt1 := rc.NewWithClient(config.Host, config.BasePath, config.Schemes, h)
securityClient := client.New(rt1, strfmt.Default)
config.WithBasePath("/v1/notification")
rt2 := rc.NewWithClient(config.Host, config.BasePath, config.Schemes, h)
notificationClient := client.New(rt2, strfmt.Default)
config.WithBasePath("/v1/organisation")
rt3 := rc.NewWithClient(config.Host, config.BasePath, config.Schemes, h)
organisationClient := client.New(rt3, strfmt.Default)
config.WithBasePath("/v1/organisation/units/associations")
rt4 := rc.NewWithClient(config.Host, config.BasePath, config.Schemes, h)
associationsClient := client.New(rt4, strfmt.Default)
config.WithBasePath("/v1/organisation")
rt5 := rc.NewWithClient(config.Host, config.BasePath, config.Schemes, h)
accountClient := client.New(rt5, strfmt.Default)
config.WithBasePath("/v1/organisation/units/")
rt6 := rc.NewWithClient(config.Host, config.BasePath, config.Schemes, h)
limitsClient := client.New(rt6, strfmt.Default)
config.WithBasePath("/v1/transaction")
rt7 := rc.NewWithClient(config.Host, config.BasePath, config.Schemes, h)
transactionClient := client.New(rt7, strfmt.Default)
config.WithBasePath("/v1/organisation/units/")
rt8 := rc.NewWithClient(config.Host, config.BasePath, config.Schemes, h)
paymentdefaultsClient := client.New(rt8, strfmt.Default)
authClient = &AuthenticatedClient{
AssociationClient: associationsClient,
SecurityClient: securityClient,
NotificationClient: notificationClient,
OrganisationClient: organisationClient,
AccountClient: accountClient,
LimitsClient: limitsClient,
PaymentdefaultsClient: paymentdefaultsClient,
TransactionClient: transactionClient,
HttpClient: h,
Config: config,
}
configureRuntime(rt1, authClient)
configureRuntime(rt2, authClient)
configureRuntime(rt3, authClient)
configureRuntime(rt4, authClient)
configureRuntime(rt5, authClient)
configureRuntime(rt6, authClient)
configureRuntime(rt7, authClient)
configureRuntime(rt8, authClient)
return authClient
}
func configureRuntime(rt *rc.Runtime, authClient *AuthenticatedClient) {
rt.Consumers["application/vnd.api+json;charset=UTF-8"] = runtime.JSONConsumer()
rt.Consumers["application/vnd.api+json"] = runtime.JSONConsumer()
}
func (r *AuthenticatedClient) Authenticate(clientId string, clientSecret string) error {
req, _ := http.NewRequest("POST", "/v1/oauth2/token", bytes.NewBufferString("grant_type=client_credentials"))
req.URL.Host = r.Config.Host
req.URL.Scheme = r.Config.Schemes[0]
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(clientId+":"+clientSecret)))
if logging.IsDebugOrHigher() {
dump, errDump := httputil.DumpRequestOut(req, true)
if errDump != nil {
log.Fatal(errDump)
}
log.Printf("[DEBUG] %s %s", req.URL.String(), string(dump))
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if logging.IsDebugOrHigher() {
dump, errDump := httputil.DumpResponse(resp, true)
if errDump != nil {
log.Fatal(errDump)
}
log.Printf("[DEBUG] %s %s", req.URL.String(), string(dump))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err.Error())
}
loginResponse, err := getLoginResponse([]byte(body))
if err != nil {
return err
}
r.AccessToken = loginResponse.AccessToken
return nil
}
func getLoginResponse(body []byte) (*LoginResponse, error) {
var s = new(LoginResponse)
err := json.Unmarshal(body, &s)
return s, err
}
type LoginResponse struct {
TokenType string `json:"token_type,omitempty"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}