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