From: Florian Forster Date: Mon, 5 Feb 2018 20:33:33 +0000 (+0100) Subject: Package gfit: Revoke the access token in addition to deleting it. X-Git-Url: https://git.verplant.org/?a=commitdiff_plain;h=a90c26dd6d2a0de773908d43e1eb3fe09b8c9a63;p=kraftakt.git Package gfit: Revoke the access token in addition to deleting it. --- diff --git a/gfit/gfit.go b/gfit/gfit.go index 3e406b4..a1d4e11 100644 --- a/gfit/gfit.go +++ b/gfit/gfit.go @@ -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") }