-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook.go
237 lines (192 loc) · 5.99 KB
/
webhook.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
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
232
233
234
235
236
237
package strava
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httputil"
"net/url"
"time"
)
func (c *Client) InitWebhook(ctx context.Context) error {
subs, err := c.GetSubscriptions(ctx)
if err != nil {
return fmt.Errorf("get subscriptions: %w", err)
}
// Clean up legacy subscriptions
for _, sub := range subs {
if err := c.DeleteSubscription(ctx, sub.ID); err != nil {
return fmt.Errorf("delete subscription: %w", err)
}
}
// Create a new subscription
subID, err := c.CreateSubscription(ctx)
if err != nil {
return fmt.Errorf("create subscription: %w", err)
}
c.subscriptionID = subID
return nil
}
func (c *Client) CloseWebhook(ctx context.Context) error {
if c.subscriptionID == 0 {
return nil
}
return c.DeleteSubscription(ctx, c.subscriptionID)
}
func (c *Client) CreateSubscription(ctx context.Context) (uint, error) {
if c.webhookCallbackURL == "" {
return 0, fmt.Errorf("webhook callback URL is not set")
}
endpoint := MustParseURL(APIBaseURL + "/push_subscriptions")
endpoint.RawQuery = url.Values{
"client_id": {c.oacfg.ClientID},
"client_secret": {c.oacfg.ClientSecret},
"callback_url": {c.webhookCallbackURL},
"verify_token": {c.webhookVerifyToken()},
}.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), nil)
if err != nil {
return 0, fmt.Errorf("create request: %w", err)
}
body, err := c.call(ctx, 0, req, 0)
if err != nil {
return 0, fmt.Errorf("call: %w", err)
}
var v struct {
ID uint `json:"id"`
}
err = json.Unmarshal(body, &v)
if err != nil {
return 0, fmt.Errorf("unmarshal response: %w", err)
}
return v.ID, nil
}
func (c *Client) DeleteSubscription(ctx context.Context, id uint) error {
endpoint := MustParseURL(fmt.Sprintf("%s/push_subscriptions/%d", APIBaseURL, id))
endpoint.RawQuery = url.Values{
"client_id": {c.oacfg.ClientID},
"client_secret": {c.oacfg.ClientSecret},
}.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, endpoint.String(), nil)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
_, err = c.call(ctx, 0, req, 0)
if err != nil {
return fmt.Errorf("call: %w", err)
}
return nil
}
type Subscription struct {
ID uint `json:"id"`
ResourceState uint `json:"resource_state"`
ApplicationID uint `json:"application_id"`
CallbackURL string `json:"callback_url"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (c *Client) GetSubscriptions(ctx context.Context) ([]*Subscription, error) {
endpoint := MustParseURL(APIBaseURL + "/push_subscriptions")
endpoint.RawQuery = url.Values{
"client_id": {c.oacfg.ClientID},
"client_secret": {c.oacfg.ClientSecret},
}.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
body, err := c.call(ctx, 0, req, 0)
if err != nil {
return nil, fmt.Errorf("call: %w", err)
}
var v []*Subscription
err = json.Unmarshal(body, &v)
if err != nil {
return nil, fmt.Errorf("unmarshal response: %w", err)
}
return v, nil
}
type EventHandler func(event Event) error
func (c *Client) RegisterEventHandler(handler EventHandler) error {
if c.subscriptionID == 0 {
return fmt.Errorf("webhook is not initialized")
}
c.eventHandlersLock.Lock()
c.eventHandlers = append(c.eventHandlers, handler)
c.eventHandlersLock.Unlock()
return nil
}
func (c *Client) webhookVerifyToken() string {
return fmt.Sprintf("strava-go-%s", c.oacfg.ClientID)
}
func (c *Client) WebhookCallback(w http.ResponseWriter, r *http.Request) {
// Dump request
dump, err := httputil.DumpRequest(r, true)
if err != nil {
c.logger.WarnContext(r.Context(), "dump request with error", slog.Any("error", err))
} else {
c.logger.DebugContext(r.Context(), "webhook callback request", slog.Any("dump", dump))
}
// Create response wrapper
rw := &responseWriter{ResponseWriter: w}
switch r.Method {
case http.MethodGet:
c.webhookValidation(rw, r)
case http.MethodPost:
c.webhookEvent(rw, r)
default:
http.Error(rw, "method not allowed", http.StatusMethodNotAllowed)
}
c.logger.DebugContext(r.Context(), "webhook callback response", slog.String("dump", rw.String()))
}
func (c *Client) webhookValidation(w http.ResponseWriter, r *http.Request) {
// Verify the token matches
if token := r.URL.Query().Get("hub.verify_token"); token != c.webhookVerifyToken() {
http.Error(w, "invalid verification token", http.StatusBadRequest)
return
}
// Echo back the challenge
challenge := r.URL.Query().Get("hub.challenge")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"hub.challenge": challenge,
})
}
type Event struct {
ObjectType EventObjectType `json:"object_type"`
ObjectID uint `json:"object_id"`
AspectType EventAspectType `json:"aspect_type"`
Updates map[string]string `json:"updates,omitempty"`
OwnerID uint `json:"owner_id"`
SubscriptionID uint `json:"subscription_id"`
EventTime uint `json:"event_time"`
}
type EventObjectType string
const (
EventObjectTypeActivity EventObjectType = "activity"
EventObjectTypeAthlete EventObjectType = "athlete"
)
type EventAspectType string
const (
EventAspectTypeCreate EventAspectType = "create"
EventAspectTypeUpdate EventAspectType = "update"
EventAspectTypeDelete EventAspectType = "delete"
)
func (c *Client) webhookEvent(w http.ResponseWriter, r *http.Request) {
var event Event
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
c.eventHandlersLock.RLock()
defer c.eventHandlersLock.RUnlock()
for _, handler := range c.eventHandlers {
go func(handler EventHandler) {
if err := handler(event); err != nil {
c.logger.Error("webhook event handled with error", "error", err)
}
}(handler)
}
w.WriteHeader(http.StatusOK)
}