Support being given an oauth2 TokenSource

This commit is contained in:
Daniel Ponte 2022-03-12 12:34:44 -05:00
parent 3e50b43650
commit edbf3599a6
3 changed files with 16 additions and 1 deletions

View File

@ -60,12 +60,15 @@ func (s *oauthTwoLeggedTokenSource) Token() (*oauth2.Token, error) {
return s.config.Token(s.ctx) return s.config.Token(s.ctx)
} }
func oauthTransport(client *Client) http.RoundTripper { func oauthTransport(client *Client) http.RoundTripper {
httpClient := &http.Client{Transport: client.client.Transport} httpClient := &http.Client{Transport: client.client.Transport}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient) ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
var tokenSource oauth2.TokenSource var tokenSource oauth2.TokenSource
if client.applicationOnlyOAuth { if client.tknSource != nil {
tokenSource = client.tknSource
} else if client.applicationOnlyOAuth {
tokenSource = &oauthTwoLeggedTokenSource{ tokenSource = &oauthTwoLeggedTokenSource{
ctx: ctx, ctx: ctx,
config: &clientcredentials.Config{ config: &clientcredentials.Config{

View File

@ -5,6 +5,9 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"golang.org/x/oauth2"
) )
// Opt is used to further configure a client upon initialization. // Opt is used to further configure a client upon initialization.
@ -65,6 +68,13 @@ func WithApplicationOnlyOAuth(o bool) Opt {
} }
} }
func WithOAuthTokenSource(tkn oauth2.TokenSource) Opt {
return func(c *Client) error {
c.tknSource = tkn
return nil
}
}
// FromEnv configures the client with values from environment variables. // FromEnv configures the client with values from environment variables.
// Supported environment variables: // Supported environment variables:
// GO_REDDIT_CLIENT_ID to set the client's id. // GO_REDDIT_CLIENT_ID to set the client's id.

View File

@ -16,6 +16,7 @@ import (
"time" "time"
"github.com/google/go-querystring/query" "github.com/google/go-querystring/query"
"golang.org/x/oauth2"
) )
const ( const (
@ -96,6 +97,7 @@ type Client struct {
Wiki *WikiService Wiki *WikiService
applicationOnlyOAuth bool applicationOnlyOAuth bool
tknSource oauth2.TokenSource
onRequestCompleted RequestCompletionCallback onRequestCompleted RequestCompletionCallback
} }