Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

78 righe
1.6 KiB

  1. // Copyright 2018 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. // +build appengine
  5. // This file applies to App Engine first generation runtimes (<= Go 1.9).
  6. package google
  7. import (
  8. "context"
  9. "sort"
  10. "strings"
  11. "sync"
  12. "golang.org/x/oauth2"
  13. "google.golang.org/appengine"
  14. )
  15. func init() {
  16. appengineTokenFunc = appengine.AccessToken
  17. appengineAppIDFunc = appengine.AppID
  18. }
  19. // See comment on AppEngineTokenSource in appengine.go.
  20. func appEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource {
  21. scopes := append([]string{}, scope...)
  22. sort.Strings(scopes)
  23. return &gaeTokenSource{
  24. ctx: ctx,
  25. scopes: scopes,
  26. key: strings.Join(scopes, " "),
  27. }
  28. }
  29. // aeTokens helps the fetched tokens to be reused until their expiration.
  30. var (
  31. aeTokensMu sync.Mutex
  32. aeTokens = make(map[string]*tokenLock) // key is space-separated scopes
  33. )
  34. type tokenLock struct {
  35. mu sync.Mutex // guards t; held while fetching or updating t
  36. t *oauth2.Token
  37. }
  38. type gaeTokenSource struct {
  39. ctx context.Context
  40. scopes []string
  41. key string // to aeTokens map; space-separated scopes
  42. }
  43. func (ts *gaeTokenSource) Token() (*oauth2.Token, error) {
  44. aeTokensMu.Lock()
  45. tok, ok := aeTokens[ts.key]
  46. if !ok {
  47. tok = &tokenLock{}
  48. aeTokens[ts.key] = tok
  49. }
  50. aeTokensMu.Unlock()
  51. tok.mu.Lock()
  52. defer tok.mu.Unlock()
  53. if tok.t.Valid() {
  54. return tok.t, nil
  55. }
  56. access, exp, err := appengineTokenFunc(ts.ctx, ts.scopes...)
  57. if err != nil {
  58. return nil, err
  59. }
  60. tok.t = &oauth2.Token{
  61. AccessToken: access,
  62. Expiry: exp,
  63. }
  64. return tok.t, nil
  65. }