improve SetAuthToken input

This commit is contained in:
Valentine 2024-03-09 18:26:46 +03:00
parent 868b87b02a
commit e6d6dc71a9
4 changed files with 18 additions and 10 deletions

View file

@ -6,7 +6,7 @@
// Test auth token
"AUTH_TOKEN": "",
"CT0": "",
"CSRF_TOKEN": "",
// Test auth with cookies
"COOKIES": "",

View file

@ -125,8 +125,10 @@ f.Write(data)
### Using AuthToken
`SetAuthToken` method simply set required cookies `auth_token` and `ct0`.
```golang
scraper.SetAuthToken(authToken, ct0)
scraper.SetAuthToken(twitterscraper.AuthToken{Token: "auth_token", CSRFToken: "ct0"})
if !scraper.IsLoggedIn() {
panic("Invalid AuthToken")
}

12
auth.go
View file

@ -405,12 +405,18 @@ func (s *Scraper) ClearCookies() {
s.client.Jar, _ = cookiejar.New(nil)
}
// Use auth_token cookie as Token and ct0 cookie as CSRFToken
type AuthToken struct {
Token string
CSRFToken string
}
// Auth using auth_token and ct0 cookies
func (s *Scraper) SetAuthToken(authToken string, ct0 string) {
func (s *Scraper) SetAuthToken(token AuthToken) {
expires := time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)
cookies := []*http.Cookie{{
Name: "auth_token",
Value: authToken,
Value: token.Token,
Path: "",
Domain: "twitter.com",
Expires: expires,
@ -423,7 +429,7 @@ func (s *Scraper) SetAuthToken(authToken string, ct0 string) {
Unparsed: nil,
}, {
Name: "ct0",
Value: ct0,
Value: token.CSRFToken,
Path: "",
Domain: "twitter.com",
Expires: expires,

View file

@ -15,7 +15,7 @@ var (
proxy = os.Getenv("PROXY")
proxyRequired = os.Getenv("PROXY_REQUIRED") != ""
authToken = os.Getenv("AUTH_TOKEN")
ct0 = os.Getenv("CT0")
csrfToken = os.Getenv("CSRF_TOKEN")
cookies = os.Getenv("COOKIES")
username = os.Getenv("TWITTER_USERNAME")
password = os.Getenv("TWITTER_PASSWORD")
@ -29,8 +29,8 @@ func init() {
return
}
if authToken != "" && ct0 != "" {
testScraper.SetAuthToken(authToken, ct0)
if authToken != "" && csrfToken != "" {
testScraper.SetAuthToken(twitterscraper.AuthToken{Token: authToken, CSRFToken: csrfToken})
if !testScraper.IsLoggedIn() {
panic("Invalid AuthToken")
}
@ -102,13 +102,13 @@ func TestLoginPassword(t *testing.T) {
}
func TestLoginToken(t *testing.T) {
if skipAuthTest || authToken == "" || ct0 == "" {
if skipAuthTest || authToken == "" || csrfToken == "" {
t.Skip("Skipping test due to environment variable")
}
scraper := newTestScraper(true)
scraper.SetAuthToken(authToken, ct0)
scraper.SetAuthToken(twitterscraper.AuthToken{Token: authToken, CSRFToken: csrfToken})
if !scraper.IsLoggedIn() {
t.Error("Expected IsLoggedIn() = true")
}