/
api.go
96 lines (77 loc) · 1.61 KB
/
api.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
package xoxoday
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"golang.org/x/oauth2"
)
type API struct {
env env
client *http.Client
}
func (a *API) makeURL(p string) string {
return a.baseURL() + p
}
func (a *API) baseURL() string {
switch a.env {
case EnvDevelopment:
return "https://stagingaccount.xoxoday.com/chef"
case EnvProduction:
return "https://accounts.xoxoday.com/chef"
}
panic("unknown env, this must never occur")
}
func (a *API) Run(r Request) ([]byte, error) {
j, err := json.Marshal(r)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
res, err := a.client.Post(
a.makeURL("/v1/oauth/api"),
"application/json",
bytes.NewReader(j),
)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %w", err)
}
if res.StatusCode != http.StatusOK {
var e Error
if err := json.Unmarshal(body, &e); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
return nil, e
}
return body, nil
}
type OAuthConfig oauth2.Config
func New(
ctx context.Context,
env env,
t Token,
oac OAuthConfig,
) *API {
verifyToken(t)
ac := &API{
env: env,
}
oac.Endpoint = oauth2.Endpoint{
TokenURL: ac.makeURL("/v1/oauth/token/" + t.TokenType),
AuthURL: ac.makeURL("/v1/oauth/token"),
}
c := oauth2.Config(oac)
ac.client = (&c).Client(ctx, &oauth2.Token{
AccessToken: t.AccessToken,
TokenType: t.TokenType,
RefreshToken: t.RefreshToken,
Expiry: t.AccessTokenExpiry.Time,
})
return ac
}