From 02d09446cefe1664211f87b4c0a852f95f2c3ef3 Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Fri, 8 Mar 2024 13:08:54 -0500 Subject: [PATCH] refactor: Move GetToken method into auth client and rename auth client from Client to Auth --- api/api.go | 6 +-- auth/auth.go | 118 +++++++++++++++++++++++++++++++++++++++++++ auth/authorize.go | 6 +-- auth/callback.go | 6 +-- auth/client.go | 57 --------------------- auth/token.go | 49 ------------------ auth/token_source.go | 4 +- 7 files changed, 129 insertions(+), 117 deletions(-) create mode 100644 auth/auth.go delete mode 100644 auth/client.go diff --git a/api/api.go b/api/api.go index 6c444c1..00a0086 100644 --- a/api/api.go +++ b/api/api.go @@ -41,7 +41,7 @@ const HelixBaseUrl = "https://api.twitch.tv/helix" type API struct { client *http.Client baseUrl *url.URL - Auth *auth.Client + Auth *auth.Auth Ads *ads.Ads Analytics *analytics.Analytics @@ -73,7 +73,7 @@ type API struct { Whispers *whispers.Whispers } -func New(client *http.Client, baseUrl *url.URL, authClient *auth.Client) *API { +func New(client *http.Client, baseUrl *url.URL, authClient *auth.Auth) *API { return &API{ client: client, baseUrl: baseUrl, @@ -117,7 +117,7 @@ func NewDefault(clientId, clientSecret, redirectUri string) *API { }, } baseUrl, _ := url.Parse(HelixBaseUrl) - authClient := auth.NewClient(clientId, clientSecret, redirectUri) + authClient := auth.New(clientId, clientSecret, redirectUri) return New(client, baseUrl, authClient) } diff --git a/auth/auth.go b/auth/auth.go new file mode 100644 index 0000000..1dd5549 --- /dev/null +++ b/auth/auth.go @@ -0,0 +1,118 @@ +package auth + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strings" + "time" + + "github.com/google/go-querystring/query" +) + +type Auth struct { + client *http.Client + + clientId string + clientSecret string + redirectUri string + + stateStorage StateStorage +} + +func New(clientId string, clientSecret string, redirectUri string) *Auth { + return NewWithClient(clientId, clientSecret, redirectUri, http.DefaultClient) +} + +func NewWithClient(clientId string, clientSecret string, redirectUri string, client *http.Client) *Auth { + return &Auth{ + client: client, + + clientId: clientId, + clientSecret: clientSecret, + redirectUri: redirectUri, + + stateStorage: NewHttpCookieStateStorage(StateStorageCookie), + } +} + +const TokenUrl = "https://id.twitch.tv/oauth2/token" + +type GetTokenParams struct { + ClientId string `url:"client_id"` + ClientSecret string `url:"client_secret"` + Code string `url:"code"` + GrantType string `url:"grant_type"` + RedirectUri string `url:"redirect_uri"` +} + +// GetToken exchanges an authorization code or refresh token for an access token. +func (a *Auth) GetToken(ctx context.Context, params *GetTokenParams) (*Token, error) { + v, err := query.Values(params) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, TokenUrl, strings.NewReader(v.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + res, err := a.client.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + statusOK := res.StatusCode >= 200 && res.StatusCode < 300 + if !statusOK { + return nil, fmt.Errorf("failed to get token (%d)", res.StatusCode) + } + + var token Token + if err := json.NewDecoder(res.Body).Decode(&token); err != nil { + return nil, err + } + + token.Expiry = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second) + + return &token, nil +} + +// GetTokenFromCode exchanges an authorization code for an access token. +// +// https://dev.twitch.tv/docs/authentication/getting-tokens-oidc/#oidc-authorization-code-grant-flow +func (a *Auth) GetTokenFromCode(ctx context.Context, code string) (*Token, error) { + return a.GetToken(ctx, &GetTokenParams{ + ClientId: a.clientId, + ClientSecret: a.clientSecret, + Code: code, + GrantType: "authorization_code", + RedirectUri: a.redirectUri, + }) +} + +// RefreshToken exchanges a refresh token for an access token. +// +// https://dev.twitch.tv/docs/authentication/refresh-tokens/ +func (a *Auth) RefreshToken(ctx context.Context, token *Token) (*Token, error) { + return a.GetToken(ctx, &GetTokenParams{ + ClientId: a.clientId, + ClientSecret: a.clientSecret, + Code: token.RefreshToken, + GrantType: "refresh_token", + RedirectUri: a.redirectUri, + }) +} + +// WithStateStorage sets the instance's state storage, +// which is used to store the state parameter between requests. +// +// By default, the http cookie state storage is used. +func (a *Auth) WithStateStorage(storage StateStorage) *Auth { + a.stateStorage = storage + + return a +} diff --git a/auth/authorize.go b/auth/authorize.go index 500616a..91d5c8e 100644 --- a/auth/authorize.go +++ b/auth/authorize.go @@ -51,7 +51,7 @@ type AuthorizeParams struct { const AuthorizeUrl = "https://id.twitch.tv/oauth2/authorize" // AuthorizeUrl returns the URL to redirect the user to for authorization. -func (c *Client) AuthorizeUrl(params *AuthorizeParams) *url.URL { +func (c *Auth) AuthorizeUrl(params *AuthorizeParams) *url.URL { v, _ := query.Values(params) v.Set("client_id", c.clientId) v.Set("redirect_uri", c.redirectUri) @@ -61,7 +61,7 @@ func (c *Client) AuthorizeUrl(params *AuthorizeParams) *url.URL { } type AuthorizeHandler struct { - client *Client + client *Auth scopes []Scope } @@ -69,7 +69,7 @@ var _ http.Handler = (*AuthorizeHandler)(nil) // AuthorizeHandler returns an http.Handler that redirects the user to the // authorization URL. -func (c *Client) AuthorizeHandler(scopes []Scope) http.Handler { +func (c *Auth) AuthorizeHandler(scopes []Scope) http.Handler { return &AuthorizeHandler{ client: c, scopes: scopes, diff --git a/auth/callback.go b/auth/callback.go index 93142d1..6d45d94 100644 --- a/auth/callback.go +++ b/auth/callback.go @@ -6,7 +6,7 @@ import ( ) type CallbackHandler struct { - client *Client + client *Auth handler TokenHandler } @@ -14,7 +14,7 @@ var _ http.Handler = (*CallbackHandler)(nil) // CallbackHandler returns an http.Handler that handles callback responses // from the twitch authentication server. -func (c *Client) CallbackHandler(h TokenHandler) http.Handler { +func (c *Auth) CallbackHandler(h TokenHandler) http.Handler { return &CallbackHandler{ client: c, handler: h, @@ -56,7 +56,7 @@ func (c *CallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { scope := q.Get("scope") _ = scope - token, err := c.client.GetToken(r.Context(), code) + token, err := c.client.GetTokenFromCode(r.Context(), code) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/auth/client.go b/auth/client.go deleted file mode 100644 index 086a18f..0000000 --- a/auth/client.go +++ /dev/null @@ -1,57 +0,0 @@ -package auth - -import "context" - -type Client struct { - clientId string - clientSecret string - redirectUri string - - stateStorage StateStorage -} - -func NewClient(clientId string, clientSecret string, redirectUri string) *Client { - return &Client{ - clientId: clientId, - clientSecret: clientSecret, - redirectUri: redirectUri, - - stateStorage: NewHttpCookieStateStorage(StateStorageCookie), - } -} - -// GetToken exchanges an authorization code for an access token. -// -// https://dev.twitch.tv/docs/authentication/getting-tokens-oidc/#oidc-authorization-code-grant-flow -func (c *Client) GetToken(ctx context.Context, code string) (*Token, error) { - return GetToken(ctx, &GetTokenParams{ - ClientId: c.clientId, - ClientSecret: c.clientSecret, - Code: code, - GrantType: "authorization_code", - RedirectUri: c.redirectUri, - }) -} - -// RefreshToken exchanges a refresh token for an access token. -// -// https://dev.twitch.tv/docs/authentication/refresh-tokens/ -func (c *Client) RefreshToken(ctx context.Context, token *Token) (*Token, error) { - return GetToken(ctx, &GetTokenParams{ - ClientId: c.clientId, - ClientSecret: c.clientSecret, - Code: token.RefreshToken, - GrantType: "refresh_token", - RedirectUri: c.redirectUri, - }) -} - -// WithStateStorage sets the instance's state storage, -// which is used to store the state parameter between requests. -// -// By default, the http cookie state storage is used. -func (c *Client) WithStateStorage(storage StateStorage) *Client { - c.stateStorage = storage - - return c -} diff --git a/auth/token.go b/auth/token.go index 505fa11..da1a5d0 100644 --- a/auth/token.go +++ b/auth/token.go @@ -1,14 +1,8 @@ package auth import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strings" "time" - "github.com/google/go-querystring/query" "golang.org/x/oauth2" ) @@ -38,49 +32,6 @@ func (t *Token) Underlying() *oauth2.Token { } } -const TokenUrl = "https://id.twitch.tv/oauth2/token" - -type GetTokenParams struct { - ClientId string `url:"client_id"` - ClientSecret string `url:"client_secret"` - Code string `url:"code"` - GrantType string `url:"grant_type"` - RedirectUri string `url:"redirect_uri"` -} - -func GetToken(ctx context.Context, params *GetTokenParams) (*Token, error) { - v, err := query.Values(params) - if err != nil { - return nil, err - } - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, TokenUrl, strings.NewReader(v.Encode())) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - res, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - - statusOK := res.StatusCode >= 200 && res.StatusCode < 300 - if !statusOK { - return nil, fmt.Errorf("failed to get token (%d)", res.StatusCode) - } - - var token Token - if err := json.NewDecoder(res.Body).Decode(&token); err != nil { - return nil, err - } - - token.Expiry = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second) - - return &token, nil -} - type TokenHandler interface { Handle(state string, token string) } diff --git a/auth/token_source.go b/auth/token_source.go index afaaf2a..0577d7b 100644 --- a/auth/token_source.go +++ b/auth/token_source.go @@ -8,13 +8,13 @@ import ( ) type TokenSource struct { - client *Client + client *Auth token *Token mu sync.Mutex } -func (c *Client) TokenSource(token *Token) oauth2.TokenSource { +func (c *Auth) TokenSource(token *Token) oauth2.TokenSource { return &TokenSource{ client: c, token: token,