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/api/api.go b/api/api.go index 6c444c1..1c25074 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.NewWithClient(clientId, clientSecret, redirectUri, client) 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 99a7795..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(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 014adf3..0000000 --- a/auth/client.go +++ /dev/null @@ -1,55 +0,0 @@ -package auth - -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(code string) (*Token, error) { - return GetToken(&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(token *Token) (*Token, error) { - return GetToken(&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 4f47e77..da1a5d0 100644 --- a/auth/token.go +++ b/auth/token.go @@ -1,13 +1,8 @@ package auth import ( - "encoding/json" - "fmt" - "net/http" - "strings" "time" - "github.com/google/go-querystring/query" "golang.org/x/oauth2" ) @@ -37,43 +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(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())) - 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 9368d6c..0577d7b 100644 --- a/auth/token_source.go +++ b/auth/token_source.go @@ -1,19 +1,20 @@ package auth import ( + "context" "sync" "golang.org/x/oauth2" ) 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, @@ -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 } 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..fbcecf0 100644 --- a/devenv.nix +++ b/devenv.nix @@ -2,14 +2,19 @@ { # 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; [ git + git-cliff twitch-cli ]; @@ -20,6 +25,16 @@ echo "Golang version: $(go version | cut -d ' ' -f 3)" ''; + gen-changelog.exec = "git cliff -o $CHANGELOG_FILE"; + release.exec = '' + version = "$(git cliff --bumped-version)" + git cliff --bump --unreleased -o $CHANGELOG_FILE + git add $CHANGELOG_FILE + git commit -m "chore(release): release $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"; start-mock-api.exec = "twitch-cli mock-api start -p $MOCK_API_PORT";