authorization flow work
This commit is contained in:
@@ -221,6 +221,7 @@ credentials:
|
|||||||
client_id: ""
|
client_id: ""
|
||||||
client_secret: "" # omit or leave blank for public-client apps
|
client_secret: "" # omit or leave blank for public-client apps
|
||||||
oauth2_access_token: "" # populated automatically by `coremarketing auth twitter`
|
oauth2_access_token: "" # populated automatically by `coremarketing auth twitter`
|
||||||
|
oauth2_refresh_token: "" #
|
||||||
linkedin:
|
linkedin:
|
||||||
# OAuth 2.0 credentials for posting. Run `coremarketing auth linkedin` to
|
# OAuth 2.0 credentials for posting. Run `coremarketing auth linkedin` to
|
||||||
# obtain access_token and author_urn automatically.
|
# obtain access_token and author_urn automatically.
|
||||||
|
|||||||
+47
-2
@@ -18,11 +18,12 @@ import (
|
|||||||
const (
|
const (
|
||||||
authURL = "https://twitter.com/i/oauth2/authorize"
|
authURL = "https://twitter.com/i/oauth2/authorize"
|
||||||
tokenURL = "https://api.twitter.com/2/oauth2/token"
|
tokenURL = "https://api.twitter.com/2/oauth2/token"
|
||||||
scopes = "tweet.read tweet.write users.read"
|
scopes = "tweet.read tweet.write users.read offline.access"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Result struct {
|
type Result struct {
|
||||||
AccessToken string
|
AccessToken string
|
||||||
|
RefreshToken string
|
||||||
}
|
}
|
||||||
|
|
||||||
func listenOnFreePort() (net.Listener, string, error) {
|
func listenOnFreePort() (net.Listener, string, error) {
|
||||||
@@ -144,6 +145,7 @@ func exchangeCode(ctx context.Context, clientID, clientSecret, code, verifier, r
|
|||||||
|
|
||||||
var out struct {
|
var out struct {
|
||||||
AccessToken string `json:"access_token"`
|
AccessToken string `json:"access_token"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(raw, &out); err != nil {
|
if err := json.Unmarshal(raw, &out); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -151,7 +153,50 @@ func exchangeCode(ctx context.Context, clientID, clientSecret, code, verifier, r
|
|||||||
if out.AccessToken == "" {
|
if out.AccessToken == "" {
|
||||||
return nil, fmt.Errorf("no access_token in response: %s", raw)
|
return nil, fmt.Errorf("no access_token in response: %s", raw)
|
||||||
}
|
}
|
||||||
return &Result{AccessToken: out.AccessToken}, nil
|
return &Result{AccessToken: out.AccessToken, RefreshToken: out.RefreshToken}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefreshTwitterToken exchanges a refresh token for a new access token.
|
||||||
|
func RefreshTwitterToken(ctx context.Context, clientID, clientSecret, refreshToken string) (*Result, error) {
|
||||||
|
data := url.Values{
|
||||||
|
"grant_type": {"refresh_token"},
|
||||||
|
"refresh_token": {refreshToken},
|
||||||
|
}
|
||||||
|
if clientSecret == "" {
|
||||||
|
data.Set("client_id", clientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(data.Encode()))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
if clientSecret != "" {
|
||||||
|
req.SetBasicAuth(clientID, clientSecret)
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
|
||||||
|
raw, _ := io.ReadAll(res.Body)
|
||||||
|
if res.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("token refresh HTTP %d: %s", res.StatusCode, raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
var out struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if out.AccessToken == "" {
|
||||||
|
return nil, fmt.Errorf("no access_token in refresh response: %s", raw)
|
||||||
|
}
|
||||||
|
return &Result{AccessToken: out.AccessToken, RefreshToken: out.RefreshToken}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// LinkedInOAuth2 runs the standard OAuth 2.0 authorization code flow for
|
// LinkedInOAuth2 runs the standard OAuth 2.0 authorization code flow for
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ type TwitterCreds struct {
|
|||||||
ClientID string `yaml:"client_id"`
|
ClientID string `yaml:"client_id"`
|
||||||
ClientSecret string `yaml:"client_secret"`
|
ClientSecret string `yaml:"client_secret"`
|
||||||
OAuth2AccessToken string `yaml:"oauth2_access_token"`
|
OAuth2AccessToken string `yaml:"oauth2_access_token"`
|
||||||
|
OAuth2RefreshToken string `yaml:"oauth2_refresh_token"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type YouTubeCreds struct {
|
type YouTubeCreds struct {
|
||||||
@@ -120,24 +121,33 @@ func (c *Config) HasLinkedInPost() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
oauth2TokenRe = regexp.MustCompile(`oauth2_access_token:\s*"[^"]*"`)
|
oauth2AccessTokenRe = regexp.MustCompile(`oauth2_access_token:\s*"[^"]*"`)
|
||||||
|
oauth2RefreshTokenRe = regexp.MustCompile(`oauth2_refresh_token:\s*"[^"]*"`)
|
||||||
liAccessTokenRe = regexp.MustCompile(`access_token:\s*"[^"]*"`)
|
liAccessTokenRe = regexp.MustCompile(`access_token:\s*"[^"]*"`)
|
||||||
liAuthorURNRe = regexp.MustCompile(`author_urn:\s*"[^"]*"`)
|
liAuthorURNRe = regexp.MustCompile(`author_urn:\s*"[^"]*"`)
|
||||||
liSectionRe = regexp.MustCompile(`^ linkedin:\s*$`)
|
liSectionRe = regexp.MustCompile(`^ linkedin:\s*$`)
|
||||||
credentialSectionRe = regexp.MustCompile(`^ [a-z]`)
|
credentialSectionRe = regexp.MustCompile(`^ [a-z]`)
|
||||||
)
|
)
|
||||||
|
|
||||||
// UpdateOAuth2Token rewrites the oauth2_access_token value in the named
|
// UpdateOAuth2Tokens rewrites both oauth2_access_token and oauth2_refresh_token
|
||||||
// config file in-place, preserving all other content and formatting.
|
// in the named config file in-place, preserving all other content and formatting.
|
||||||
func UpdateOAuth2Token(path, token string) error {
|
// If refreshToken is empty the refresh_token field is left unchanged.
|
||||||
|
func UpdateOAuth2Tokens(path, accessToken, refreshToken string) error {
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
updated := oauth2TokenRe.ReplaceAllLiteralString(string(data), `oauth2_access_token: "`+token+`"`)
|
s := string(data)
|
||||||
if updated == string(data) {
|
|
||||||
|
updated := oauth2AccessTokenRe.ReplaceAllLiteralString(s, `oauth2_access_token: "`+accessToken+`"`)
|
||||||
|
if updated == s {
|
||||||
return fmt.Errorf("oauth2_access_token field not found in %s", path)
|
return fmt.Errorf("oauth2_access_token field not found in %s", path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if refreshToken != "" {
|
||||||
|
updated = oauth2RefreshTokenRe.ReplaceAllLiteralString(updated, `oauth2_refresh_token: "`+refreshToken+`"`)
|
||||||
|
}
|
||||||
|
|
||||||
return os.WriteFile(path, []byte(updated), 0600)
|
return os.WriteFile(path, []byte(updated), 0600)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -57,8 +57,31 @@ func main() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// If Twitter is configured but has no access token, run auth before the TUI.
|
// If Twitter is configured but has no access token, try a silent refresh
|
||||||
|
// first (if a refresh token is stored), then fall back to full re-auth.
|
||||||
if cfg.Credentials.Twitter.ClientID != "" && !cfg.HasTwitterPost() {
|
if cfg.Credentials.Twitter.ClientID != "" && !cfg.HasTwitterPost() {
|
||||||
|
tw := cfg.Credentials.Twitter
|
||||||
|
if tw.OAuth2RefreshToken != "" {
|
||||||
|
result, err := auth.RefreshTwitterToken(context.Background(), tw.ClientID, tw.ClientSecret, tw.OAuth2RefreshToken)
|
||||||
|
if err == nil {
|
||||||
|
if saveErr := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); saveErr != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Warning: could not save refreshed token: %v\n", saveErr)
|
||||||
|
}
|
||||||
|
cfg, err = config.Load(cfgPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Token refresh failed (%v), re-authorizing...\n", err)
|
||||||
|
runAuth(cfgPath)
|
||||||
|
cfg, err = config.Load(cfgPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
fmt.Println("No Twitter access token found. Starting authorization...")
|
fmt.Println("No Twitter access token found. Starting authorization...")
|
||||||
runAuth(cfgPath)
|
runAuth(cfgPath)
|
||||||
cfg, err = config.Load(cfgPath)
|
cfg, err = config.Load(cfgPath)
|
||||||
@@ -67,6 +90,7 @@ func main() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Resolve data file paths relative to the config file so they're always
|
// Resolve data file paths relative to the config file so they're always
|
||||||
// written to the same place regardless of where the binary is invoked from.
|
// written to the same place regardless of where the binary is invoked from.
|
||||||
@@ -211,7 +235,7 @@ func runAuth(cfgPath string) {
|
|||||||
fmt.Printf("Authorized as @%s\n", username)
|
fmt.Printf("Authorized as @%s\n", username)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := config.UpdateOAuth2Token(cfgPath, result.AccessToken); err != nil {
|
if err := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Could not save token automatically: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Could not save token automatically: %v\n", err)
|
||||||
fmt.Printf("\nAdd this to %s manually:\n oauth2_access_token: \"%s\"\n", cfgPath, result.AccessToken)
|
fmt.Printf("\nAdd this to %s manually:\n oauth2_access_token: \"%s\"\n", cfgPath, result.AccessToken)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
|
|||||||
Reference in New Issue
Block a user