本文整理汇总了Golang中golang.org/x/oauth2.ReuseTokenSource函数的典型用法代码示例。如果您正苦于以下问题:Golang ReuseTokenSource函数的具体用法?Golang ReuseTokenSource怎么用?Golang ReuseTokenSource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ReuseTokenSource函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: MakeClient
func MakeClient(token string) *github.Client {
var client *http.Client
var transport http.RoundTripper
if *useMemoryCache {
transport = httpcache.NewMemoryCacheTransport()
} else {
transport = http.DefaultTransport
}
if len(token) > 0 {
rateLimitTransport := &RateLimitRoundTripper{
delegate: transport,
// Global limit is 5000 Q/Hour, try to only use 1800 to make room for other apps
throttle: util.NewTokenBucketRateLimiter(0.5, 10),
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
client = &http.Client{
Transport: &oauth2.Transport{
Base: rateLimitTransport,
Source: oauth2.ReuseTokenSource(nil, ts),
},
}
} else {
rateLimitTransport := &RateLimitRoundTripper{
delegate: transport,
throttle: util.NewTokenBucketRateLimiter(0.01, 10),
}
client = &http.Client{
Transport: rateLimitTransport,
}
}
return github.NewClient(client)
}
示例2: New
// New returns a new Amazon Cloud Drive "acd" Client. configFile must exist and must be a valid JSON decodable into Config.
func New(configFile string) (*Client, error) {
config, err := loadConfig(configFile)
if err != nil {
return nil, err
}
ts, err := token.New(config.TokenFile)
if err != nil {
return nil, err
}
c := &Client{
config: config,
cacheFile: config.CacheFile,
httpClient: &http.Client{
Timeout: config.Timeout,
Transport: &oauth2.Transport{
Source: oauth2.ReuseTokenSource(nil, ts),
},
},
}
if err := setEndpoints(c); err != nil {
return nil, err
}
return c, nil
}
示例3: NewRefreshTokenSource
// NewRefreshTokenSource returns a token source that obtains its initial token
// based on the provided config and the refresh token.
func NewRefreshTokenSource(config *oauth2.Config, refreshToken string) oauth2.TokenSource {
var noInitialToken *oauth2.Token = nil
return oauth2.ReuseTokenSource(noInitialToken, config.TokenSource(
oauth2.NoContext, // TODO: maybe accept a context later.
&oauth2.Token{RefreshToken: refreshToken},
))
}
示例4: TokenSource
// TokenSource returns a TokenSource that returns t until t expires,
// automatically refreshing it as necessary using the provided context and the
// client ID and client secret.
//
// Most users will use Config.Client instead.
func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource {
source := &tokenSource{
ctx: ctx,
conf: c,
}
return oauth2.ReuseTokenSource(nil, source)
}
示例5: TokenSource
// TokenSource returns a ReuseTokenSource.
func (c *Config) TokenSource(ctx context.Context, t *oauth2.Token) oauth2.TokenSource {
tts := &TokenStorageSource{
source: c.Config.TokenSource(ctx, t),
config: c,
}
return oauth2.ReuseTokenSource(t, tts)
}
示例6: tokenSource
// tokenSource returns a reusable oauth2.TokenSource.
// When expired, a new token will be obtained using cred.RefreshToken
// and stored in a persistent db.
// The returned TokenSource valid only within provided context c.
func (cred *oauth2Credentials) tokenSource(c context.Context) oauth2.TokenSource {
t := &oauth2.Token{
AccessToken: cred.AccessToken,
Expiry: cred.Expiry,
}
return oauth2.ReuseTokenSource(t, &tokenRefresher{c, cred})
}
示例7: PreExecute
// PreExecute will initialize the Config. It MUST be run before the config
// may be used to get information from Github
func (config *Config) PreExecute() error {
if len(config.Org) == 0 {
glog.Fatalf("--organization is required.")
}
if len(config.Project) == 0 {
glog.Fatalf("--project is required.")
}
token := config.Token
if len(token) == 0 && len(config.TokenFile) != 0 {
data, err := ioutil.ReadFile(config.TokenFile)
if err != nil {
glog.Fatalf("error reading token file: %v", err)
}
token = strings.TrimSpace(string(data))
}
// We need to get our Transport/RoundTripper in order based on arguments
// oauth2 Transport // if we have an auth token
// zeroCacheRoundTripper // if we are using the cache want faster timeouts
// webCacheRoundTripper // if we are using the cache
// callLimitRoundTripper ** always
// [http.DefaultTransport] ** always implicit
var transport http.RoundTripper
callLimitTransport := &callLimitRoundTripper{
remaining: tokenLimit + 500, // put in 500 so we at least have a couple to check our real limits
resetTime: time.Now().Add(1 * time.Minute),
}
config.apiLimit = callLimitTransport
transport = callLimitTransport
if config.useMemoryCache {
t := httpcache.NewMemoryCacheTransport()
t.Transport = transport
zeroCacheTransport := &zeroCacheRoundTripper{
delegate: t,
}
transport = zeroCacheTransport
}
if len(token) > 0 {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
transport = &oauth2.Transport{
Base: transport,
Source: oauth2.ReuseTokenSource(nil, ts),
}
}
client := &http.Client{
Transport: transport,
}
config.client = github.NewClient(client)
config.ResetAPICount()
return nil
}
示例8: newAltTokenSource
func newAltTokenSource(tokenURL string) oauth2.TokenSource {
client := oauth2.NewClient(oauth2.NoContext, google.ComputeTokenSource(""))
a := &altTokenSource{
oauthClient: client,
tokenURL: tokenURL,
}
return oauth2.ReuseTokenSource(nil, a)
}
示例9: newOauthClient
func newOauthClient(authTokenPath string) (*http.Client, error) {
token, err := oauth2.ReuseTokenSource(nil, gobSource{path: authTokenPath, base: browserSource{}}).Token()
if err != nil {
log.Infof("problem exchanging code: %s", err)
return nil, err
}
return oauth2Config.Client(context.Background(), token), nil
}
示例10: NewClientFrom
// NewClientFrom returns an http client which will use the provided func
// as a source for oauth tokens. The underlying transport handles automatic
// retries and logging that is useful for integration tests and agents.
func NewClientFrom(src oauth2.TokenSource) *http.Client {
// Wrapping in a ReuseTokenSource will cache the returned token so that src
// is only called when a new token is needed.
return newAuthenticatedClient(
oauth2.ReuseTokenSource(nil, src),
transport(),
)
}
示例11: GetTokenSource
// GetTokenSource builds a new oauth2.TokenSource that uses the ttnctl config to store the token
func GetTokenSource(ctx log.Interface) oauth2.TokenSource {
if tokenSource != nil {
return tokenSource
}
token := getStoredToken(ctx)
source := oauth2.ReuseTokenSource(token, getAccountServerTokenSource(token))
tokenSource = &ttnctlTokenSource{ctx, source}
return tokenSource
}
示例12: newAltTokenSource
func newAltTokenSource(tokenURL string) oauth2.TokenSource {
client := oauth2.NewClient(oauth2.NoContext, google.ComputeTokenSource(""))
a := &altTokenSource{
oauthClient: client,
tokenURL: tokenURL,
throttle: util.NewTokenBucketRateLimiter(tokenURLQPS, tokenURLBurst),
}
return oauth2.ReuseTokenSource(nil, a)
}
示例13: RunCommand
func (c *googinitCmd) RunCommand(args []string) error {
var (
err error
clientId string
clientSecret string
oauthConfig *oauth2.Config
)
if c.storageType != "drive" && c.storageType != "cloud" {
return cmdmain.UsageError("Invalid storage type: must be drive for Google Drive or cloud for Google Cloud Storage.")
}
clientId, clientSecret = getClientInfo()
switch c.storageType {
case "drive":
oauthConfig = &oauth2.Config{
Scopes: []string{drive.Scope},
Endpoint: google.Endpoint,
ClientID: clientId,
ClientSecret: clientSecret,
RedirectURL: oauthutil.TitleBarRedirectURL,
}
case "cloud":
oauthConfig = &oauth2.Config{
Scopes: []string{storage.ScopeReadWrite},
Endpoint: google.Endpoint,
ClientID: clientId,
ClientSecret: clientSecret,
RedirectURL: oauthutil.TitleBarRedirectURL,
}
}
token, err := oauth2.ReuseTokenSource(nil, &oauthutil.TokenSource{
Config: oauthConfig,
AuthCode: func() string {
fmt.Fprintf(cmdmain.Stdout, "Get auth code from:\n\n")
fmt.Fprintf(cmdmain.Stdout, "%v\n\n", oauthConfig.AuthCodeURL("", oauth2.AccessTypeOffline, oauth2.ApprovalForce))
return prompt("Enter auth code:")
},
}).Token()
if err != nil {
return fmt.Errorf("could not acquire token: %v", err)
}
fmt.Fprintf(cmdmain.Stdout, "\nYour Google auth object:\n\n")
enc := json.NewEncoder(cmdmain.Stdout)
authObj := map[string]string{
"client_id": clientId,
"client_secret": clientSecret,
"refresh_token": token.RefreshToken,
}
enc.Encode(authObj)
fmt.Fprint(cmdmain.Stdout, "\n\nFor server-config.json, your 'googlecloudstorage' value (update with your bucket name and path):\n\n")
fmt.Fprintf(cmdmain.Stdout, "%s:%s:%s:bucketName[/optional/dir]\n", clientId, clientSecret, token.RefreshToken)
return nil
}
示例14: ForceRefreshToken
// ForceRefreshToken forces a refresh of the access token
func ForceRefreshToken(ctx log.Interface) {
tokenSource := GetTokenSource(ctx).(*ttnctlTokenSource)
token, err := tokenSource.Token()
if err != nil {
ctx.WithError(err).Fatal("Could not get access token")
}
token.Expiry = time.Now().Add(-1 * time.Second)
tokenSource.source = oauth2.ReuseTokenSource(token, getAccountServerTokenSource(token))
tokenSource.Token()
}
示例15: tokenSource
func tokenSource() oauth2.TokenSource {
var tokensource oauth2.TokenSource
tokenSource, err := google.DefaultTokenSource(oauth2.NoContext)
if err == nil {
return tokenSource
}
oauthConfig := &oauth2.Config{
// The client-id and secret should be for an "Installed Application" when using
// the CLI. Later we'll use a web application with a callback.
ClientID: readFile(stagingPrefix() + "client-id.dat"),
ClientSecret: readFile(stagingPrefix() + "client-secret.dat"),
Endpoint: google.Endpoint,
Scopes: []string{
compute.DevstorageFullControlScope,
compute.ComputeScope,
compute.CloudPlatformScope,
"https://www.googleapis.com/auth/sqlservice",
"https://www.googleapis.com/auth/sqlservice.admin",
},
RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
}
tokenFileName := stagingPrefix() + "token.dat"
tokenFile := tokenCacheFile(tokenFileName)
tokenSource = oauth2.ReuseTokenSource(nil, tokenFile)
token, err := tokenSource.Token()
if err != nil {
log.Printf("Error getting token from %s: %v", tokenFileName, err)
log.Printf("Get auth code from %v", oauthConfig.AuthCodeURL("my-state"))
fmt.Print("\nEnter auth code: ")
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
authCode := strings.TrimSpace(sc.Text())
token, err = oauthConfig.Exchange(oauth2.NoContext, authCode)
if err != nil {
log.Fatalf("Error exchanging auth code for a token: %v", err)
}
if err := tokenFile.WriteToken(token); err != nil {
log.Fatalf("Error writing to %s: %v", tokenFileName, err)
}
tokenSource = oauth2.ReuseTokenSource(token, nil)
}
return tokensource
}