Remove query string when redirecting user.
[kraftakt.git] / gfitsync.go
1 package gfitsync
2
3 import (
4         "context"
5         "crypto/hmac"
6         "crypto/sha1"
7         "encoding/base64"
8         "encoding/json"
9         "fmt"
10         "io/ioutil"
11         "net/http"
12         "net/url"
13         "time"
14
15         legacy_context "golang.org/x/net/context"
16         "golang.org/x/oauth2"
17         "golang.org/x/oauth2/fitbit"
18         "google.golang.org/appengine"
19         "google.golang.org/appengine/datastore"
20         "google.golang.org/appengine/delay"
21         "google.golang.org/appengine/log"
22         "google.golang.org/appengine/user"
23 )
24
25 const csrfToken = "@CSRFTOKEN@"
26
27 // var delayedHandleNotifications = delay.Func("handleNotifications", func(ctx legacy_context.Context, payload []byte) error {
28 //      return handleNotifications(ctx, payload)
29 // })
30 var delayedHandleNotifications = delay.Func("handleNotifications", handleNotifications)
31
32 var oauthConfig = &oauth2.Config{
33         ClientID:     "@FITBIT_CLIENT_ID@",
34         ClientSecret: "@FITBIT_CLIENT_SECRET@",
35         Endpoint:     fitbit.Endpoint,
36         RedirectURL:  "https://fitbit-gfit-sync.appspot.com/fitbit/grant", // TODO(octo): make full URL
37         Scopes:       []string{"activity"},
38 }
39
40 type storedToken struct {
41         Email string
42         oauth2.Token
43 }
44
45 func init() {
46         http.HandleFunc("/setup", setupHandler)
47         http.Handle("/fitbit/grant", AuthenticatedHandler(fitbitGrantHandler))
48         http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
49         http.Handle("/", AuthenticatedHandler(indexHandler))
50 }
51
52 // ContextHandler implements http.Handler
53 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) error
54
55 func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
56         ctx := appengine.NewContext(r)
57
58         if err := hndl(ctx, w, r); err != nil {
59                 http.Error(w, err.Error(), http.StatusInternalServerError)
60                 return
61         }
62 }
63
64 type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Request, *user.User) error
65
66 func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
67         ctx := appengine.NewContext(r)
68
69         u := user.Current(ctx)
70         if u == nil {
71                 url, err := user.LoginURL(ctx, r.URL.String())
72                 if err != nil {
73                         http.Error(w, err.Error(), http.StatusInternalServerError)
74                         return
75                 }
76                 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
77                 return
78         }
79
80         err := datastore.RunInTransaction(ctx, func(ctx legacy_context.Context) error {
81                 key := RootKey(ctx, u)
82                 if err := datastore.Get(ctx, key, &struct{}{}); err != datastore.ErrNoSuchEntity {
83                         return err // may be nil
84                 }
85                 _, err := datastore.Put(ctx, key, &struct{}{})
86                 return err
87         }, nil)
88         if err != nil {
89                 http.Error(w, err.Error(), http.StatusInternalServerError)
90                 return
91         }
92
93         if err := hndl(ctx, w, r, u); err != nil {
94                 http.Error(w, err.Error(), http.StatusInternalServerError)
95                 return
96         }
97 }
98
99 func RootKey(ctx context.Context, u *user.User) *datastore.Key {
100         return datastore.NewKey(ctx, "User", u.Email, 0, nil)
101 }
102
103 func indexHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *user.User) error {
104         var (
105                 tok       oauth2.Token
106                 haveToken bool
107         )
108
109         key := datastore.NewKey(ctx, "Token", "Fitbit", 0, RootKey(ctx, u))
110         err := datastore.Get(ctx, key, &tok)
111         if err != nil && err != datastore.ErrNoSuchEntity {
112                 return err
113         }
114         if err == nil {
115                 haveToken = true
116         }
117
118         fmt.Fprintf(w, "u = %v, tok = %v, haveToken = %v\n", u, tok, haveToken)
119
120         // TODO(octo): print summary to user
121         return nil
122 }
123
124 func setupHandler(w http.ResponseWriter, r *http.Request) {
125         url := oauthConfig.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
126         http.Redirect(w, r, url, http.StatusTemporaryRedirect)
127 }
128
129 func fitbitGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *user.User) error {
130         if state := r.FormValue("state"); state != csrfToken {
131                 return fmt.Errorf("invalid state parameter: %q", state)
132         }
133
134         tok, err := oauthConfig.Exchange(ctx, r.FormValue("code"))
135         if err != nil {
136                 return err
137         }
138
139         key := datastore.NewKey(ctx, "Token", "Fitbit", 0, RootKey(ctx, u))
140         if _, err := datastore.Put(ctx, key, tok); err != nil {
141                 return err
142         }
143
144         c := oauthConfig.Client(ctx, tok)
145
146         // create a subscription
147         url := fmt.Sprintf("https://api.fitbit.com/1/user/-/activities/apiSubscriptions/%s.json",
148                 RootKey(ctx, u).Encode())
149         res, err := c.Post(url, "", nil)
150         if err != nil {
151                 return err
152         }
153         defer res.Body.Close()
154
155         redirectURL := r.URL
156         redirectURL.Path = "/"
157         redirectURL.RawQuery = ""
158         redirectURL.Fragment = ""
159         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
160         return nil
161 }
162
163 type fitbitNotification struct {
164         CollectionType string `json:"collectionType"`
165         Date           string `json:"date"`
166         OwnerID        string `json:"ownerId"`
167         OwnerType      string `json:"ownerType"`
168         SubscriptionID string `json:"subscriptionId"`
169 }
170
171 func (n *fitbitNotification) URLValues() url.Values {
172         return url.Values{
173                 "CollectionType": []string{n.CollectionType},
174                 "Date":           []string{n.Date},
175                 "OwnerID":        []string{n.OwnerID},
176                 "OwnerType":      []string{n.OwnerType},
177                 "SubscriptionID": []string{n.SubscriptionID},
178         }
179 }
180
181 func (n *fitbitNotification) URL() string {
182         return fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/date/%s.json",
183                 n.OwnerID, n.CollectionType, n.Date)
184 }
185
186 func checkSignature(ctx context.Context, payload []byte, rawSig string) bool {
187         base64Sig, err := url.QueryUnescape(rawSig)
188         if err != nil {
189                 log.Errorf(ctx, "QueryUnescape(%q) = %v", rawSig, err)
190                 return false
191         }
192         signatureGot, err := base64.StdEncoding.DecodeString(base64Sig)
193         if err != nil {
194                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", base64Sig, err)
195                 return false
196         }
197
198         mac := hmac.New(sha1.New, []byte(oauthConfig.ClientSecret+"&"))
199         mac.Write(payload)
200         signatureWant := mac.Sum(nil)
201
202         return hmac.Equal(signatureGot, signatureWant)
203 }
204
205 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
206 // subscription. It verifies the payload, splits it into individual
207 // notifications and adds it to the taskqueue service.
208 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
209         defer r.Body.Close()
210
211         fitbitTimeout := 3 * time.Second
212         ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
213         defer cancel()
214
215         // this is used when setting up a new subscriber in the UI. Once set
216         // up, this code path should not be triggered.
217         if verify := r.FormValue("verify"); verify != "" {
218                 if verify == "@FITBIT_SUBSCRIBER_CODE@" {
219                         w.WriteHeader(http.StatusNoContent)
220                 } else {
221                         w.WriteHeader(http.StatusNotFound)
222                 }
223                 return nil
224         }
225
226         data, err := ioutil.ReadAll(r.Body)
227         if err != nil {
228                 return err
229         }
230
231         // Fitbit recommendation: "If signature verification fails, you should
232         // respond with a 404"
233         if !checkSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
234                 w.WriteHeader(http.StatusNotFound)
235                 return nil
236         }
237
238         if err := delayedHandleNotifications.Call(ctx, data); err != nil {
239                 return err
240         }
241
242         w.WriteHeader(http.StatusCreated)
243         return nil
244 }
245
246 // handleNotifications parses fitbit notifications and requests the individual
247 // activities from Fitbit. It is executed asynchronously via the delay package.
248 func handleNotifications(ctx context.Context, payload []byte) error {
249         var notifications []fitbitNotification
250         if err := json.Unmarshal(payload, notifications); err != nil {
251                 return err
252         }
253
254         for _, n := range notifications {
255                 if n.CollectionType != "activities" {
256                         continue
257                 }
258
259                 if err := handleNotification(ctx, &n); err != nil {
260                         log.Errorf(ctx, "handleNotification() = %v", err)
261                         continue
262                 }
263         }
264
265         return nil
266 }
267
268 func handleNotification(ctx context.Context, n *fitbitNotification) error {
269         rootKey, err := datastore.DecodeKey(n.SubscriptionID)
270         if err != nil {
271                 return err
272         }
273         key := datastore.NewKey(ctx, "Token", "Fitbit", 0, rootKey)
274
275         var tok oauth2.Token
276         if err := datastore.Get(ctx, key, &tok); err != nil {
277                 return err
278         }
279
280         c := oauthConfig.Client(ctx, &tok)
281         res, err := c.Get(n.URL())
282         if err != nil {
283                 return err
284         }
285
286         log.Infof(ctx, "GET %s = %v", n.URL(), res)
287         return nil
288 }