-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauthclient.go
65 lines (51 loc) · 1.35 KB
/
oauthclient.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
package client
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
)
const (
oauthURL = "https://auth.us-east-2.propeldata.com/oauth2/token"
)
type OauthClient struct {
client *http.Client
}
type OAuthToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
func NewOauthClient() *OauthClient {
client := newHttpClient(Options{
Timeout: 2 * time.Second,
Retries: 3,
Delay: 5 * time.Millisecond,
})
return &OauthClient{client: client}
}
func (c *OauthClient) OAuthToken(ctx context.Context, clientID string, clientSecret string) (*OAuthToken, error) {
payload := url.Values{}
payload.Set("grant_type", "client_credentials")
req, err := http.NewRequestWithContext(ctx, http.MethodPost, oauthURL, strings.NewReader(payload.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to build request: %w", err)
}
req.Header.Add("content-type", "application/x-www-form-urlencoded")
req.SetBasicAuth(clientID, clientSecret)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unable to fetch access token; status=%d", resp.StatusCode)
}
var token *OAuthToken
if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
return nil, err
}
return token, nil
}