Package gfit: Revoke the access token in addition to deleting it.
authorFlorian Forster <ff@octo.it>
Mon, 5 Feb 2018 20:33:33 +0000 (21:33 +0100)
committerFlorian Forster <ff@octo.it>
Mon, 5 Feb 2018 20:56:29 +0000 (21:56 +0100)
gfit/gfit.go

index 3e406b4..a1d4e11 100644 (file)
@@ -3,18 +3,22 @@ package gfit
 import (
        "context"
        "fmt"
+       "io/ioutil"
        "net/http"
+       "net/url"
        "strings"
        "time"
 
        "github.com/octo/kraftakt/app"
        "github.com/octo/kraftakt/fitbit"
+       "github.com/octo/retry"
        "golang.org/x/oauth2"
        oauth2google "golang.org/x/oauth2/google"
        fitness "google.golang.org/api/fitness/v1"
        "google.golang.org/api/googleapi"
        "google.golang.org/appengine"
        "google.golang.org/appengine/log"
+       "google.golang.org/appengine/urlfetch"
 )
 
 const (
@@ -88,7 +92,38 @@ func NewClient(ctx context.Context, u *app.User) (*Client, error) {
        }, nil
 }
 
+func (c *Client) revokeToken(ctx context.Context) error {
+       tok, err := c.appUser.Token(ctx, "Google")
+       if err != nil {
+               return err
+       }
+
+       httpClient := urlfetch.Client(ctx)
+       httpClient.Transport = retry.NewTransport(httpClient.Transport)
+
+       url := "https://accounts.google.com/o/oauth2/revoke?token=" + url.QueryEscape(tok.AccessToken)
+       res, err := httpClient.Get(url)
+       if err != nil {
+               return fmt.Errorf("GET %s: %v", url, err)
+       }
+       defer res.Body.Close()
+
+       if res.StatusCode != http.StatusOK {
+               if data, err := ioutil.ReadAll(res.Body); err == nil {
+                       return fmt.Errorf("GET %s: %s", url, data)
+               } else {
+                       return fmt.Errorf("GET %s: %s", url, res.Status)
+               }
+       }
+
+       return nil
+}
+
 func (c *Client) DeleteToken(ctx context.Context) error {
+       if err := c.revokeToken(ctx); err != nil {
+               log.Warningf(ctx, "revokeToken() = %v", err)
+       }
+
        return c.appUser.DeleteToken(ctx, "Google")
 }