-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.go
154 lines (141 loc) · 4.32 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
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
package airpin
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"github.com/GoogleCloudPlatform/functions-framework-go/functions"
"github.com/cloudevents/sdk-go/v2/event"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
)
func init() {
functions.HTTP("exchangeCodeForTokens", exchangeCodeForTokens)
functions.HTTP("saveTokens", saveTokens)
functions.CloudEvent("refreshAccessToken", refreshAccessToken)
}
type response struct {
AccessToken string `json:"access_token"`
ResponseType string `json:"response_type"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
// A job must be scheduled in Google Cloud Scheduler to run this every 30 days,
// which is the expiry period set by Pinterest. Google Cloud Scheduler uses a
// crontab format, which is stateless, so it's not possible to configure it to
// execute "every 30 days". Instead, "0 0 */30 * *" will run on the first of
// each month, as well as the 31st of each month, so there's an unnecessary
// extra refresh in months that have more than 30 days.
func refreshAccessToken(ctx context.Context, e event.Event) error {
smc, err := secretmanager.NewClient(ctx)
if err != nil {
panic(err)
}
defer smc.Close()
rt := getRefreshToken(ctx, smc)
uri := "https://api.pinterest.com/v5/oauth/token"
data := url.Values{}
data.Set("grant_type", "refresh_token")
data.Set("refresh_token", rt)
data.Set("scopes", "ads:read,pins:read,user_accounts:read")
req, err := http.NewRequest("POST", uri, strings.NewReader(data.Encode()))
if err != nil {
panic(err)
}
b64client := getB64Client(ctx, smc)
req.Header.Add("Authorization", "Basic "+b64client)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
panic(err)
}
body, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
if res.StatusCode != http.StatusOK {
panic(res.Status + ": " + string(body))
}
var r response
if err = json.Unmarshal(body, &r); err != nil {
panic(err)
}
saveAccessToken(ctx, smc, r.AccessToken)
// TODO disable last access token
return nil
}
func getB64Client(ctx context.Context, client *secretmanager.Client) string {
req := &secretmanagerpb.AccessSecretVersionRequest{
Name: "projects/YOUR_PROJECT/secrets/b64client/versions/latest",
}
res, err := client.AccessSecretVersion(ctx, req)
if err != nil {
panic(err)
}
return string(res.Payload.Data)
}
func exchangeCodeForTokens(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
smc, err := secretmanager.NewClient(ctx)
if err != nil {
panic(err)
}
defer smc.Close()
code := r.URL.Query().Get("code")
uri := "https://api.pinterest.com/v5/oauth/token"
redirectUri := "https://YOUR_PROJECT_SUBDOMAIN.cloudfunctions.net/saveTokens"
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("code", code)
data.Set("redirect_uri", redirectUri)
req, err := http.NewRequest("POST", uri, strings.NewReader(data.Encode()))
if err != nil {
panic(err)
}
b64client := getB64Client(ctx, smc)
req.Header.Add("Authorization", "Basic "+b64client)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
panic(err)
}
body, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
if res.StatusCode != http.StatusOK {
panic(res.Status + ": " + string(body))
}
var d response
if err = json.Unmarshal(body, &d); err != nil {
panic(err)
}
}
func saveTokens(w http.ResponseWriter, r *http.Request) {
}
func getRefreshToken(ctx context.Context, client *secretmanager.Client) string {
req := &secretmanagerpb.AccessSecretVersionRequest{
Name: "projects/YOUR_PROJECT/secrets/pinterest-refresh-token/versions/latest",
}
res, err := client.AccessSecretVersion(ctx, req)
if err != nil {
panic(err)
}
return string(res.Payload.Data)
}
func saveAccessToken(ctx context.Context, client *secretmanager.Client, token string) {
req := &secretmanagerpb.AddSecretVersionRequest{
Parent: "projects/YOUR_PROJECT/secrets/pinterest-token",
Payload: &secretmanagerpb.SecretPayload{
Data: []byte(token),
},
}
if _, err := client.AddSecretVersion(ctx, req); err != nil {
panic(err)
}
}