-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.go
72 lines (58 loc) · 1.49 KB
/
oauth.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
package ups
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type OAuthToken struct {
TokenType string `json:"token_type"`
IssuedAt string `json:"issued_at"`
ClientID string `json:"client_id"`
AccessToken string `json:"access_token"`
ExpiresIn string `json:"expires_in"`
Status string `json:"status"`
}
func (c *Client) getOAuthAccessToken(ctx context.Context) error {
data := url.Values{}
data.Set("grant_type", "client_credentials")
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("%s%s/token", c.environment, oauthURL), strings.NewReader(data.Encode()))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(c.clientID, c.clientSecret)
err = c.logHTTPRequest(req)
if err != nil {
return err
}
res, err := c.httpClient.Do(req)
if err != nil {
return err
}
err = c.logHTTPResponse(res)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("unknown status code: (%d) %s", res.StatusCode, res.Status)
}
var token OAuthToken
decoder := json.NewDecoder(res.Body)
decoder.DisallowUnknownFields()
err = decoder.Decode(&token)
if err != nil {
return err
}
expiresIn, err := strconv.Atoi(token.ExpiresIn)
if err != nil {
return err
}
c.accessToken = token.TokenType + " " + token.AccessToken
c.accessTokenIsValidUntil = time.Now().Add(time.Duration(expiresIn) * time.Second)
return nil
}