You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

90 regels
2.3 KiB

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