-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchoruspro.go
More file actions
231 lines (180 loc) · 4.91 KB
/
Copy pathchoruspro.go
File metadata and controls
231 lines (180 loc) · 4.91 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
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package choruspro
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/oauth2"
)
const (
defaultBaseURL = "https://sandbox-api.piste.gouv.fr/"
defaultAuthURL = "https://sandbox-oauth.piste.gouv.fr/"
)
// ClientConfig contains the configuration for the client
type ClientConfig struct {
// Piste URL
BaseUrl string
// Piste OAuth URL
AuthUrl string
// Piste client ID
ClientId string
// Piste client secret
ClientSecret string
// Chorus Pro technical credentials (login:password base64 encoded)
Login string
}
// Client is used for HTTP requests to the Chorus Pro API
// and it routes these requests through the Piste API
type Client struct {
// HTTP client used to communicate with the API.
client *http.Client
// Piste URL
BaseUrl *url.URL
// Piste OAuth URL
AuthUrl *url.URL
// Piste client ID
clientId string
// Piste client secret
clientSecret string
// OAuth token used for authentication
token *oauth2.Token
// Chorus Pro technical account credentials (login:password base64 encoded)
login string
// Shared between services
common service
// Services
Factures *FacturesService
Structures *StructuresService
Transverses *TransversesService
Utilisateurs *UtilisateursService
}
type service struct {
client *Client
}
func NewClient() *Client {
c := &Client{client: http.DefaultClient}
c.initialize()
return c
}
func (c *Client) WithConfig(config *ClientConfig) (*Client, error) {
var err error
c.BaseUrl, err = url.Parse(config.BaseUrl)
if err != nil {
return nil, err
}
c.AuthUrl, err = url.Parse(config.AuthUrl)
if err != nil {
return nil, err
}
c.clientId = config.ClientId
c.clientSecret = config.ClientSecret
c.login = config.Login
return c, err
}
func (c *Client) initialize() {
c.common.client = c
c.BaseUrl, _ = url.Parse(defaultBaseURL)
c.AuthUrl, _ = url.Parse(defaultAuthURL)
c.Factures = (*FacturesService)(&c.common)
c.Structures = (*StructuresService)(&c.common)
c.Transverses = (*TransversesService)(&c.common)
c.Utilisateurs = (*UtilisateursService)(&c.common)
}
// newRequest creates an API request for the Chorus Pro API.
func (c *Client) newRequest(ctx context.Context, method, url string, body interface{}) (*http.Request, error) {
if !strings.HasSuffix(c.BaseUrl.Path, "/") {
return nil, fmt.Errorf("BaseURL must have a trailing slash, but %q does not", c.BaseUrl)
}
u, err := c.BaseUrl.Parse(url)
if err != nil {
return nil, err
}
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, method, u.String(), bytes.NewBuffer(data))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json;charset=utf-8")
req.Header.Add("cpro-account", c.login)
return req, nil
}
// doRequest performs an HTTP request to the Chorus Pro API
// and routes it through the Piste API. It also handles
// authentication and token refresh.
func (c *Client) doRequest(ctx context.Context, req *http.Request, obj interface{}) error {
// Check if token is valid, if not, get a new one
if !c.token.Valid() {
token, err := getOAuthToken(c.clientId, c.clientSecret, c.AuthUrl)
if err != nil {
return err
}
// Update token
c.token = token
req.Header.Add("Authorization", fmt.Sprintf("Bearer %v", c.token.AccessToken))
}
res, err := c.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
if res.StatusCode == http.StatusBadRequest {
return parseError(res)
}
return fmt.Errorf("choruspro: %v", res.Status)
}
data, err := io.ReadAll(res.Body)
// Print
log.Println(string(data))
if err != nil {
return nil
}
return json.Unmarshal(data, obj)
}
// getOAuthToken retrieves an OAuth token from the Piste API
func getOAuthToken(clientId, clientSecret string, authUrl *url.URL) (*oauth2.Token, error) {
u, _ := authUrl.Parse("api/oauth/token")
c := http.DefaultClient
data := url.Values{}
data.Set("client_id", clientId)
data.Set("client_secret", clientSecret)
data.Set("grant_type", "client_credentials")
encodedData := data.Encode()
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(encodedData))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
var token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type,omitempty"`
ExpiresIn int16 `json:"expires_in,omitempty"`
}
res, err := c.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("choruspro: %v", res.Status)
}
err = json.NewDecoder(res.Body).Decode(&token)
if err != nil {
return nil, err
}
tok := &oauth2.Token{
AccessToken: token.AccessToken,
TokenType: token.TokenType,
Expiry: time.Now().Add(time.Duration(token.ExpiresIn) * time.Second),
}
return tok, nil
}