import (
"context"
"fmt"
+ "net/http"
"github.com/google/uuid"
legacy_context "golang.org/x/net/context"
"golang.org/x/oauth2"
"google.golang.org/appengine/datastore"
+ "google.golang.org/appengine/log"
)
type User struct {
}
func (u *User) SetToken(ctx context.Context, svc string, tok *oauth2.Token) error {
- key := datastore.NewKey(ctx, "Token", "Fitbit", 0, u.key)
+ key := datastore.NewKey(ctx, "Token", svc, 0, u.key)
_, err := datastore.Put(ctx, key, tok)
return err
}
+
+func (u *User) OAuthClient(ctx context.Context, svc string, cfg *oauth2.Config) (*http.Client, error) {
+ key := datastore.NewKey(ctx, "Token", svc, 0, u.key)
+
+ var tok oauth2.Token
+ if err := datastore.Get(ctx, key, &tok); err != nil {
+ return nil, err
+ }
+
+ src := cfg.TokenSource(ctx, &tok)
+ return oauth2.NewClient(ctx, &persistingTokenSource{
+ ctx: ctx,
+ t: &tok,
+ src: src,
+ key: key,
+ }), nil
+}
+
+type persistingTokenSource struct {
+ ctx context.Context
+ t *oauth2.Token
+ src oauth2.TokenSource
+ key *datastore.Key
+}
+
+func (s *persistingTokenSource) Token() (*oauth2.Token, error) {
+ tok, err := s.src.Token()
+ if err != nil {
+ return nil, err
+ }
+
+ if s.t.RefreshToken != tok.RefreshToken {
+ if _, err := datastore.Put(s.ctx, s.key, tok); err != nil {
+ log.Errorf(s.ctx, "persisting OAuth token in datastore failed: %v", err)
+ }
+ }
+
+ s.t = tok
+ return tok, nil
+}