appengine.go 2.2 KB

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