From edbf3599a687039d7f122cd6a1f00f4ac2af658a Mon Sep 17 00:00:00 2001 From: Daniel Ponte Date: Sat, 12 Mar 2022 12:34:44 -0500 Subject: [PATCH] Support being given an oauth2 TokenSource --- reddit/reddit-oauth.go | 5 ++++- reddit/reddit-options.go | 10 ++++++++++ reddit/reddit.go | 2 ++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/reddit/reddit-oauth.go b/reddit/reddit-oauth.go index 89e22bc..a3d1908 100644 --- a/reddit/reddit-oauth.go +++ b/reddit/reddit-oauth.go @@ -60,12 +60,15 @@ func (s *oauthTwoLeggedTokenSource) Token() (*oauth2.Token, error) { return s.config.Token(s.ctx) } + func oauthTransport(client *Client) http.RoundTripper { httpClient := &http.Client{Transport: client.client.Transport} ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient) var tokenSource oauth2.TokenSource - if client.applicationOnlyOAuth { + if client.tknSource != nil { + tokenSource = client.tknSource + } else if client.applicationOnlyOAuth { tokenSource = &oauthTwoLeggedTokenSource{ ctx: ctx, config: &clientcredentials.Config{ diff --git a/reddit/reddit-options.go b/reddit/reddit-options.go index 04cfab1..f5a1dfe 100644 --- a/reddit/reddit-options.go +++ b/reddit/reddit-options.go @@ -5,6 +5,9 @@ import ( "net/http" "net/url" "os" + + + "golang.org/x/oauth2" ) // 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. // Supported environment variables: // GO_REDDIT_CLIENT_ID to set the client's id. diff --git a/reddit/reddit.go b/reddit/reddit.go index 225c84d..77fd2ad 100644 --- a/reddit/reddit.go +++ b/reddit/reddit.go @@ -16,6 +16,7 @@ import ( "time" "github.com/google/go-querystring/query" + "golang.org/x/oauth2" ) const ( @@ -96,6 +97,7 @@ type Client struct { Wiki *WikiService applicationOnlyOAuth bool + tknSource oauth2.TokenSource onRequestCompleted RequestCompletionCallback }