fix authorization
This commit is contained in:
@@ -16,11 +16,22 @@ import (
|
|||||||
|
|
||||||
const apiBase = "https://api.twitter.com/2"
|
const apiBase = "https://api.twitter.com/2"
|
||||||
|
|
||||||
|
// TokenRefresher is called when PostTweet receives a 401. It should obtain a
|
||||||
|
// new access token (and optionally rotate the refresh token) and persist both.
|
||||||
|
type TokenRefresher func(ctx context.Context) (accessToken, refreshToken string, err error)
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
bearerToken string
|
bearerToken string
|
||||||
oauth2AccessToken string
|
oauth2AccessToken string
|
||||||
maxResults int
|
maxResults int
|
||||||
http *http.Client
|
http *http.Client
|
||||||
|
tokenRefresher TokenRefresher
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetTokenRefresher registers a callback invoked automatically on 401 so that
|
||||||
|
// an expired OAuth2 access token is refreshed and the post is retried once.
|
||||||
|
func (c *Client) SetTokenRefresher(fn TokenRefresher) {
|
||||||
|
c.tokenRefresher = fn
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(bearerToken, oauth2AccessToken string, maxResults int) *Client {
|
func New(bearerToken, oauth2AccessToken string, maxResults int) *Client {
|
||||||
@@ -80,28 +91,45 @@ func (c *Client) SearchTweets(ctx context.Context, query string, since time.Time
|
|||||||
return c.tweetsToItems(resp, "", models.SourceTwitterSearch, appName), nil
|
return c.tweetsToItems(resp, "", models.SourceTwitterSearch, appName), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// PostTweet posts a tweet using OAuth 2.0 user context.
|
// PostTweet posts a tweet using OAuth 2.0 user context. On a 401 it attempts
|
||||||
|
// one automatic token refresh (if a TokenRefresher was registered) and retries.
|
||||||
func (c *Client) PostTweet(ctx context.Context, text string) (string, error) {
|
func (c *Client) PostTweet(ctx context.Context, text string) (string, error) {
|
||||||
|
tweetURL, unauthorized, err := c.postTweet(ctx, text)
|
||||||
|
if unauthorized && c.tokenRefresher != nil {
|
||||||
|
newAccess, _, refreshErr := c.tokenRefresher(ctx)
|
||||||
|
if refreshErr != nil {
|
||||||
|
return "", fmt.Errorf("post tweet HTTP 401 and token refresh failed: %w", refreshErr)
|
||||||
|
}
|
||||||
|
c.oauth2AccessToken = newAccess
|
||||||
|
tweetURL, _, err = c.postTweet(ctx, text)
|
||||||
|
}
|
||||||
|
return tweetURL, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) postTweet(ctx context.Context, text string) (tweetURL string, unauthorized bool, err error) {
|
||||||
endpoint := apiBase + "/tweets"
|
endpoint := apiBase + "/tweets"
|
||||||
payload := map[string]string{"text": text}
|
payload := map[string]string{"text": text}
|
||||||
body, _ := json.Marshal(payload)
|
body, _ := json.Marshal(payload)
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(body)))
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(body)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", false, err
|
||||||
}
|
}
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
req.Header.Set("Authorization", "Bearer "+c.oauth2AccessToken)
|
req.Header.Set("Authorization", "Bearer "+c.oauth2AccessToken)
|
||||||
|
|
||||||
res, err := c.http.Do(req)
|
res, err := c.http.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", false, err
|
||||||
}
|
}
|
||||||
defer res.Body.Close()
|
defer res.Body.Close()
|
||||||
|
|
||||||
raw, _ := io.ReadAll(res.Body)
|
raw, _ := io.ReadAll(res.Body)
|
||||||
|
if res.StatusCode == http.StatusUnauthorized {
|
||||||
|
return "", true, fmt.Errorf("post tweet HTTP %d: %s", res.StatusCode, raw)
|
||||||
|
}
|
||||||
if res.StatusCode != http.StatusCreated {
|
if res.StatusCode != http.StatusCreated {
|
||||||
return "", fmt.Errorf("post tweet HTTP %d: %s", res.StatusCode, raw)
|
return "", false, fmt.Errorf("post tweet HTTP %d: %s", res.StatusCode, raw)
|
||||||
}
|
}
|
||||||
|
|
||||||
var out struct {
|
var out struct {
|
||||||
@@ -111,9 +139,9 @@ func (c *Client) PostTweet(ctx context.Context, text string) (string, error) {
|
|||||||
} `json:"data"`
|
} `json:"data"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(raw, &out); err != nil {
|
if err := json.Unmarshal(raw, &out); err != nil {
|
||||||
return "", err
|
return "", false, err
|
||||||
}
|
}
|
||||||
return "https://x.com/" + out.Data.ID, nil
|
return "https://x.com/" + out.Data.ID, false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// BuildSearchQuery constructs an X search query from hashtags.
|
// BuildSearchQuery constructs an X search query from hashtags.
|
||||||
|
|||||||
@@ -123,6 +123,20 @@ func main() {
|
|||||||
cfg.Credentials.Twitter.OAuth2AccessToken,
|
cfg.Credentials.Twitter.OAuth2AccessToken,
|
||||||
cfg.Settings.MaxResults,
|
cfg.Settings.MaxResults,
|
||||||
)
|
)
|
||||||
|
if tw := cfg.Credentials.Twitter; tw.OAuth2RefreshToken != "" {
|
||||||
|
currentRefreshToken := tw.OAuth2RefreshToken
|
||||||
|
twClient.SetTokenRefresher(func(ctx context.Context) (string, string, error) {
|
||||||
|
result, err := auth.RefreshTwitterToken(ctx, tw.ClientID, tw.ClientSecret, currentRefreshToken)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
if saveErr := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); saveErr != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Warning: could not save refreshed token: %v\n", saveErr)
|
||||||
|
}
|
||||||
|
currentRefreshToken = result.RefreshToken
|
||||||
|
return result.AccessToken, result.RefreshToken, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var ytClient *youtube.Client
|
var ytClient *youtube.Client
|
||||||
|
|||||||
Reference in New Issue
Block a user