• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang oauth2.ReuseTokenSource函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/oauth2.ReuseTokenSource函数的典型用法代码示例。如果您正苦于以下问题:Golang ReuseTokenSource函数的具体用法?Golang ReuseTokenSource怎么用?Golang ReuseTokenSource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ReuseTokenSource函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
开发者ID:jdef,项目名称:contrib,代码行数:32,代码来源:github.go


示例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
}
开发者ID:herrsebi,项目名称:acd,代码行数:27,代码来源:client.go


示例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},
	))
}
开发者ID:edrex-duex,项目名称:go4,代码行数:9,代码来源:oauth.go


示例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)
}
开发者ID:Richardphp,项目名称:noms,代码行数:12,代码来源:clientcredentials.go


示例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)
}
开发者ID:Muswell,项目名称:oauthpersist,代码行数:8,代码来源:storage.go


示例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})
}
开发者ID:pathikdevani,项目名称:ioweb2015,代码行数:11,代码来源:auth.go


示例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
}
开发者ID:timstclair,项目名称:kube-contrib,代码行数:61,代码来源:github.go


示例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)
}
开发者ID:cjnygard,项目名称:origin,代码行数:8,代码来源:token_source.go


示例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
}
开发者ID:nvanbenschoten,项目名称:cockroach-prod,代码行数:8,代码来源:auth_util.go


示例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(),
	)
}
开发者ID:mbrukman,项目名称:cloudsql-proxy,代码行数:11,代码来源:auth.go


示例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
}
开发者ID:TheThingsNetwork,项目名称:ttn,代码行数:10,代码来源:account.go


示例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)
}
开发者ID:chenzhen411,项目名称:kubernetes,代码行数:9,代码来源:token_source.go


示例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
}
开发者ID:camlistore,项目名称:camlistore,代码行数:57,代码来源:googinit.go


示例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()
}
开发者ID:TheThingsNetwork,项目名称:ttn,代码行数:11,代码来源:account.go


示例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
}
开发者ID:rdterner,项目名称:build,代码行数:43,代码来源:create.go


示例16: PreExecute

// PreExecute will initialize the GithubConfig. It MUST be run before the config
// may be used to get information from Github
func (config *GithubConfig) 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 = string(data)
	}

	transport := http.DefaultTransport
	if config.useMemoryCache {
		transport = httpcache.NewMemoryCacheTransport()
	}

	// convert from queries per hour to queries per second
	config.RateLimit = config.RateLimit / 3600
	// ignore the configured rate limit if you don't have a token.
	// only get 60 requests per hour!
	if len(token) == 0 {
		glog.Warningf("Ignoring --rate-limit because no token data available")
		config.RateLimit = 0.01
		config.RateLimitBurst = 10
	}
	rateLimitTransport := &rateLimitRoundTripper{
		delegate: transport,
		throttle: util.NewTokenBucketRateLimiter(config.RateLimit, config.RateLimitBurst),
	}

	client := &http.Client{
		Transport: rateLimitTransport,
	}
	if len(token) > 0 {
		ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
		client = &http.Client{
			Transport: &oauth2.Transport{
				Base:   rateLimitTransport,
				Source: oauth2.ReuseTokenSource(nil, ts),
			},
		}
	}
	config.client = github.NewClient(client)
	config.analytics.lastAPIReset = time.Now()
	return nil
}
开发者ID:wojtek-t,项目名称:contrib,代码行数:54,代码来源:github.go


示例17: RunCommand

func (c *gceCmd) RunCommand(args []string) error {
	if c.verbose {
		gce.Verbose = true
	}
	if c.project == "" {
		return cmdmain.UsageError("Missing --project flag.")
	}
	if (c.certFile == "") != (c.keyFile == "") {
		return cmdmain.UsageError("--cert and --key must both be given together.")
	}
	if c.certFile == "" && c.hostname == "" {
		return cmdmain.UsageError("Either --hostname, or --cert & --key must provided.")
	}
	config := gce.NewOAuthConfig(readFile(clientIdDat), readFile(clientSecretDat))
	config.RedirectURL = "urn:ietf:wg:oauth:2.0:oob"

	instConf := &gce.InstanceConf{
		Name:     c.instName,
		Project:  c.project,
		Machine:  c.machine,
		Zone:     c.zone,
		CertFile: c.certFile,
		KeyFile:  c.keyFile,
		Hostname: c.hostname,
	}
	if c.sshPub != "" {
		instConf.SSHPub = strings.TrimSpace(readFile(c.sshPub))
	}

	depl := &gce.Deployer{
		Client: oauth2.NewClient(oauth2.NoContext, oauth2.ReuseTokenSource(nil, &oauthutil.TokenSource{
			Config:    config,
			CacheFile: c.project + "-token.json",
			AuthCode: func() string {
				fmt.Println("Get auth code from:")
				fmt.Printf("%v\n", config.AuthCodeURL("my-state", oauth2.AccessTypeOffline, oauth2.ApprovalForce))
				fmt.Println("Enter auth code:")
				sc := bufio.NewScanner(os.Stdin)
				sc.Scan()
				return strings.TrimSpace(sc.Text())
			},
		})),
		Conf: instConf,
	}
	inst, err := depl.Create(context.TODO())
	if err != nil {
		return err
	}

	log.Printf("Instance is up at %s", inst.NetworkInterfaces[0].AccessConfigs[0].NatIP)
	return nil
}
开发者ID:Jimmy99,项目名称:camlistore,代码行数:52,代码来源:gce.go


示例18: sourceForToken

// sourceForToken returns a TokenSource based on the following rules:
//   - if token is not "" it is used as the bearer token for the source
//   - if the binary is running on GCE, tokens will be retrieved from the metadata server
//   - otherwise, a source is returned which returns an error each time it is used.
func sourceForToken(token string) oauth2.TokenSource {
	if token != "" {
		return oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
	}

	tok, err := gceToken()
	if err == nil {
		return oauth2.ReuseTokenSource(tok, tokenFunc(gceToken))
	}
	log.Printf("Can't find GCE metadata server: %v", err)
	return tokenFunc(func() (*oauth2.Token, error) {
		return nil, errors.New("must provide a token on command line or run on GCE")
	})
}
开发者ID:mbrukman,项目名称:cloudsql-proxy,代码行数:18,代码来源:auth.go


示例19: PreExecute

func (config *GithubConfig) 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 = string(data)
	}

	var client *http.Client
	var transport http.RoundTripper
	if config.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,
		}
	}
	config.client = github.NewClient(client)
	return nil
}
开发者ID:sigma,项目名称:kubernetes-contrib,代码行数:49,代码来源:github.go


示例20: RefreshFacebookTokens

func RefreshFacebookTokens(c *gin.Context) {
	if auth.IsAuthenticated(c) {
		user := auth.GetUser(c)
		if user.LoginType == "facebook" {
			aecontext := appengine.NewContext(c.Request)
			conf := FBConfig()
			toksource := conf.TokenSource(aecontext, &user.Token)
			sourceToken := oauth2.ReuseTokenSource(&user.Token, toksource)
			client := oauth2.NewClient(aecontext, sourceToken)
			client.Get("...")
			t, _ := sourceToken.Token()
			user.Token = *t
			auth.UpdateUser(c, &user)
			log.Debugf(aecontext, fmt.Sprintf("refresh tokens %#v", t))
		}
	}
}
开发者ID:sankark,项目名称:kyp,代码行数:17,代码来源:facebook.go



注:本文中的golang.org/x/oauth2.ReuseTokenSource函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang oauth2.StaticTokenSource函数代码示例发布时间:2022-05-28
下一篇:
Golang oauth2.NewClient函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap