appengine.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2014 The oauth2 Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package google
  5. import (
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "golang.org/x/net/context"
  11. "golang.org/x/oauth2"
  12. )
  13. // Set at init time by appengine_hook.go. If nil, we're not on App Engine.
  14. var appengineTokenFunc func(c context.Context, scopes ...string) (token string, expiry time.Time, err error)
  15. // AppEngineTokenSource returns a token source that fetches tokens
  16. // issued to the current App Engine application's service account.
  17. // If you are implementing a 3-legged OAuth 2.0 flow on App Engine
  18. // that involves user accounts, see oauth2.Config instead.
  19. //
  20. // The provided context must have come from appengine.NewContext.
  21. func AppEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource {
  22. if appengineTokenFunc == nil {
  23. panic("google: AppEngineTokenSource can only be used on App Engine.")
  24. }
  25. scopes := append([]string{}, scope...)
  26. sort.Strings(scopes)
  27. return &appEngineTokenSource{
  28. ctx: ctx,
  29. scopes: scopes,
  30. key: strings.Join(scopes, " "),
  31. }
  32. }
  33. // aeTokens helps the fetched tokens to be reused until their expiration.
  34. var (
  35. aeTokensMu sync.Mutex
  36. aeTokens = make(map[string]*tokenLock) // key is space-separated scopes
  37. )
  38. type tokenLock struct {
  39. mu sync.Mutex // guards t; held while fetching or updating t
  40. t *oauth2.Token
  41. }
  42. type appEngineTokenSource struct {
  43. ctx context.Context
  44. scopes []string
  45. key string // to aeTokens map; space-separated scopes
  46. }
  47. func (ts *appEngineTokenSource) Token() (*oauth2.Token, error) {
  48. if appengineTokenFunc == nil {
  49. panic("google: AppEngineTokenSource can only be used on App Engine.")
  50. }
  51. aeTokensMu.Lock()
  52. tok, ok := aeTokens[ts.key]
  53. if !ok {
  54. tok = &tokenLock{}
  55. aeTokens[ts.key] = tok
  56. }
  57. aeTokensMu.Unlock()
  58. tok.mu.Lock()
  59. defer tok.mu.Unlock()
  60. if tok.t.Valid() {
  61. return tok.t, nil
  62. }
  63. access, exp, err := appengineTokenFunc(ts.ctx, ts.scopes...)
  64. if err != nil {
  65. return nil, err
  66. }
  67. tok.t = &oauth2.Token{
  68. AccessToken: access,
  69. Expiry: exp,
  70. }
  71. return tok.t, nil
  72. }