X-Git-Url: https://git.octo.it/?p=kraftakt.git;a=blobdiff_plain;f=app%2Fuser.go;h=e47a5cc4ae16a617ad7a1eba5543737138887954;hp=8465c2ce582b982686ea379bc462b12685efc972;hb=62a15962f1a331a998b6fe6b724b814490be5fe4;hpb=6e353fc58f08533be15182536e7b0c5099c098b8 diff --git a/app/user.go b/app/user.go index 8465c2c..e47a5cc 100644 --- a/app/user.go +++ b/app/user.go @@ -3,11 +3,13 @@ package app 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 { @@ -78,7 +80,47 @@ func (u *User) Token(ctx context.Context, svc string) (*oauth2.Token, error) { } 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 +}