From 01bc01979e9c4d03066404b7aacad950834aaf5b Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Fri, 8 Mar 2024 01:28:33 -0500 Subject: [PATCH 1/6] chore: Add git cliff for auto generated changelog --- CHANGELOG.md | 17 ++++++++++ cliff.toml | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++ devenv.nix | 3 ++ 3 files changed, 109 insertions(+) create mode 100644 CHANGELOG.md create mode 100644 cliff.toml diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6247162 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +## [1.1.3] - 2024-03-08 + +### ๐Ÿ› Bug Fixes + +- Create endpoint make utility to build endpoints + +## [1.0.3] - 2024-03-07 + +### ๐Ÿ› Bug Fixes + +- Use urlencoded body for get token request + + diff --git a/cliff.toml b/cliff.toml new file mode 100644 index 0000000..d6425f9 --- /dev/null +++ b/cliff.toml @@ -0,0 +1,89 @@ +# git-cliff ~ default configuration file +# https://git-cliff.org/docs/configuration +# +# Lines starting with "#" are comments. +# Configuration options are organized into tables and keys. +# See documentation for more information on available options. + +[changelog] +# changelog header +header = """ +# Changelog\n +All notable changes to this project will be documented in this file.\n +""" +# template for the changelog body +# https://keats.github.io/tera/docs/#introduction +body = """ +{% if version %}\ + ## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }} +{% else %}\ + ## [unreleased] +{% endif %}\ +{% for group, commits in commits | group_by(attribute="group") %} + ### {{ group | striptags | trim | upper_first }} + {% for commit in commits %} + - {% if commit.scope %}*({{ commit.scope }})* {% endif %}\ + {% if commit.breaking %}[**breaking**] {% endif %}\ + {{ commit.message | upper_first }}\ + {% endfor %} +{% endfor %}\n +""" +# template for the changelog footer +footer = """ + +""" +# remove the leading and trailing s +trim = true +# postprocessors +postprocessors = [ + # { pattern = '', replace = "https://github.com/orhun/git-cliff" }, # replace repository URL +] + +[git] +# parse the commits based on https://www.conventionalcommits.org +conventional_commits = true +# filter out the commits that are not conventional +filter_unconventional = true +# process each line of a commit as an individual commit +split_commits = false +# regex for preprocessing the commit messages +commit_preprocessors = [ + # Replace issue numbers + #{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, + # Check spelling of the commit with https://github.com/crate-ci/typos + # If the spelling is incorrect, it will be automatically fixed. + #{ pattern = '.*', replace_command = 'typos --write-changes -' }, +] +# regex for parsing and grouping commits +commit_parsers = [ + { message = "^feat", group = "๐Ÿš€ Features" }, + { message = "^fix", group = "๐Ÿ› Bug Fixes" }, + { message = "^doc", group = "๐Ÿ“š Documentation" }, + { message = "^perf", group = "โšก Performance" }, + { message = "^refactor", group = "๐Ÿšœ Refactor" }, + { message = "^style", group = "๐ŸŽจ Styling" }, + { message = "^test", group = "๐Ÿงช Testing" }, + { message = "^chore\\(release\\): prepare for", skip = true }, + { message = "^chore\\(deps.*\\)", skip = true }, + { message = "^chore\\(pr\\)", skip = true }, + { message = "^chore\\(pull\\)", skip = true }, + { message = "^chore|ci", group = "โš™๏ธ Miscellaneous Tasks" }, + { body = ".*security", group = "๐Ÿ›ก๏ธ Security" }, + { message = "^revert", group = "โ—€๏ธ Revert" }, +] +# protect breaking changes from being skipped due to matching a skipping commit_parser +protect_breaking_commits = false +# filter out the commits that are not matched by commit parsers +filter_commits = false +# regex for matching git tags +# tag_pattern = "v[0-9].*" +# regex for skipping tags +# skip_tags = "" +# regex for ignoring tags +# ignore_tags = "" +# sort the tags topologically +topo_order = false +# sort the commits inside sections by oldest/newest order +sort_commits = "oldest" +# limit the number of commits included in the changelog. +# limit_commits = 42 diff --git a/devenv.nix b/devenv.nix index 4a2bdd5..2233e5c 100644 --- a/devenv.nix +++ b/devenv.nix @@ -10,6 +10,7 @@ # https://devenv.sh/packages/ packages = with pkgs; [ git + git-cliff twitch-cli ]; @@ -20,6 +21,8 @@ echo "Golang version: $(go version | cut -d ' ' -f 3)" ''; + changelog.exec = "git cliff -o CHANGELOG.md"; + gen-mock-data.exec = "twitch-cli mock-api generate"; rm-mock-data.exec = "rm $MOCK_DATA_PATH"; start-mock-api.exec = "twitch-cli mock-api start -p $MOCK_API_PORT"; From adf49ce4bbfd4af852b751cc5336ad010b729827 Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Fri, 8 Mar 2024 13:05:54 -0500 Subject: [PATCH 2/6] feat: Add context to GetToken endpoint --- auth/callback.go | 2 +- auth/client.go | 10 ++++++---- auth/token.go | 11 +++++++++-- auth/token_source.go | 3 ++- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/auth/callback.go b/auth/callback.go index 99a7795..93142d1 100644 --- a/auth/callback.go +++ b/auth/callback.go @@ -56,7 +56,7 @@ func (c *CallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { scope := q.Get("scope") _ = scope - token, err := c.client.GetToken(code) + token, err := c.client.GetToken(r.Context(), code) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/auth/client.go b/auth/client.go index 014adf3..086a18f 100644 --- a/auth/client.go +++ b/auth/client.go @@ -1,5 +1,7 @@ package auth +import "context" + type Client struct { clientId string clientSecret string @@ -21,8 +23,8 @@ func NewClient(clientId string, clientSecret string, redirectUri string) *Client // 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(code string) (*Token, error) { - return GetToken(&GetTokenParams{ +func (c *Client) GetToken(ctx context.Context, code string) (*Token, error) { + return GetToken(ctx, &GetTokenParams{ ClientId: c.clientId, ClientSecret: c.clientSecret, Code: code, @@ -34,8 +36,8 @@ func (c *Client) GetToken(code string) (*Token, error) { // RefreshToken exchanges a refresh token for an access token. // // https://dev.twitch.tv/docs/authentication/refresh-tokens/ -func (c *Client) RefreshToken(token *Token) (*Token, error) { - return GetToken(&GetTokenParams{ +func (c *Client) RefreshToken(ctx context.Context, token *Token) (*Token, error) { + return GetToken(ctx, &GetTokenParams{ ClientId: c.clientId, ClientSecret: c.clientSecret, Code: token.RefreshToken, diff --git a/auth/token.go b/auth/token.go index 4f47e77..505fa11 100644 --- a/auth/token.go +++ b/auth/token.go @@ -1,6 +1,7 @@ package auth import ( + "context" "encoding/json" "fmt" "net/http" @@ -47,13 +48,19 @@ type GetTokenParams struct { RedirectUri string `url:"redirect_uri"` } -func GetToken(params *GetTokenParams) (*Token, error) { +func GetToken(ctx context.Context, params *GetTokenParams) (*Token, error) { v, err := query.Values(params) if err != nil { return nil, err } - res, err := http.Post(TokenUrl, "application/x-www-form-urlencoded", strings.NewReader(v.Encode())) + 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 } diff --git a/auth/token_source.go b/auth/token_source.go index 9368d6c..afaaf2a 100644 --- a/auth/token_source.go +++ b/auth/token_source.go @@ -1,6 +1,7 @@ package auth import ( + "context" "sync" "golang.org/x/oauth2" @@ -28,7 +29,7 @@ func (ts *TokenSource) Token() (*oauth2.Token, error) { return ts.token.Underlying(), nil } - token, err := ts.client.RefreshToken(ts.token) + token, err := ts.client.RefreshToken(context.Background(), ts.token) if err != nil { return nil, err } From 02d09446cefe1664211f87b4c0a852f95f2c3ef3 Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Fri, 8 Mar 2024 13:08:54 -0500 Subject: [PATCH 3/6] 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, From 9c4e63c2008acba523a9e05e75ace84854440af0 Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Fri, 8 Mar 2024 13:12:13 -0500 Subject: [PATCH 4/6] refactor: Change api client to pass http client to auth client --- api/api.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/api.go b/api/api.go index 00a0086..1c25074 100644 --- a/api/api.go +++ b/api/api.go @@ -117,7 +117,7 @@ func NewDefault(clientId, clientSecret, redirectUri string) *API { }, } baseUrl, _ := url.Parse(HelixBaseUrl) - authClient := auth.New(clientId, clientSecret, redirectUri) + authClient := auth.NewWithClient(clientId, clientSecret, redirectUri, client) return New(client, baseUrl, authClient) } From 7fa9815a3763075f0811ee5e5e99d799e0826afd Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Fri, 8 Mar 2024 13:24:43 -0500 Subject: [PATCH 5/6] chore(devenv): Add release script and rename changelog script to gen-changelog --- devenv.nix | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/devenv.nix b/devenv.nix index 2233e5c..222e459 100644 --- a/devenv.nix +++ b/devenv.nix @@ -2,10 +2,14 @@ { # https://devenv.sh/basics/ - env.PROJECT_NAME = "go-twitch"; + env = { + PROJECT_NAME = "go-twitch"; - env.MOCK_DATA_PATH = "~/.config/twitch-cli/eventCache.db"; - env.MOCK_API_PORT = "3000"; + MOCK_DATA_PATH = "~/.config/twitch-cli/eventCache.db"; + MOCK_API_PORT = "3000"; + + CHANGELOG_FILE = "CHANGELOG.md"; + }; # https://devenv.sh/packages/ packages = with pkgs; [ @@ -21,7 +25,15 @@ echo "Golang version: $(go version | cut -d ' ' -f 3)" ''; - changelog.exec = "git cliff -o CHANGELOG.md"; + gen-changelog.exec = "git cliff -o $CHANGELOG_FILE"; + release.exec = '' + version = "$(git cliff --bumped-version)" + gen-changelog + git add $CHANGELOG_FILE + git commit -m "chore: Update changelog and bump version" + git tag "$version" -m "Release $version" + git push --tags + ''; gen-mock-data.exec = "twitch-cli mock-api generate"; rm-mock-data.exec = "rm $MOCK_DATA_PATH"; From 08f0281e988d520fde05077b6435f5b53579e97d Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Fri, 8 Mar 2024 13:40:10 -0500 Subject: [PATCH 6/6] fix(devenv): Fix release changelog generation and commit message --- devenv.nix | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/devenv.nix b/devenv.nix index 222e459..fbcecf0 100644 --- a/devenv.nix +++ b/devenv.nix @@ -28,9 +28,9 @@ gen-changelog.exec = "git cliff -o $CHANGELOG_FILE"; release.exec = '' version = "$(git cliff --bumped-version)" - gen-changelog + git cliff --bump --unreleased -o $CHANGELOG_FILE git add $CHANGELOG_FILE - git commit -m "chore: Update changelog and bump version" + git commit -m "chore(release): release $version" git tag "$version" -m "Release $version" git push --tags '';