Improve logout

drop session in Twitter
This commit is contained in:
Alexander Sheiko 2023-05-10 22:24:32 +03:00
parent e86c2fa4ce
commit 90f9a71721
3 changed files with 28 additions and 14 deletions

19
api.go
View file

@ -3,7 +3,7 @@ package twitterscraper
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"time"
)
@ -48,9 +48,13 @@ func (s *Scraper) RequestAPI(req *http.Request, target interface{}) error {
}
defer resp.Body.Close()
content, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
// private profiles return forbidden, but also data
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusForbidden {
content, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("response status %s: %s", resp.Status, content)
}
@ -58,13 +62,10 @@ func (s *Scraper) RequestAPI(req *http.Request, target interface{}) error {
s.guestToken = ""
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
if target == nil {
return nil
}
// fmt.Println(string(b))
return json.Unmarshal(b, target)
return json.Unmarshal(content, target)
}
// GetGuestToken from Twitter API
@ -81,7 +82,7 @@ func (s *Scraper) GetGuestToken() error {
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}

13
auth.go
View file

@ -11,6 +11,7 @@ import (
const (
loginURL = "https://api.twitter.com/1.1/onboarding/task.json"
logoutURL = "https://api.twitter.com/1.1/account/logout.json"
bearerToken2 = "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
)
@ -230,11 +231,21 @@ func (s *Scraper) Login(credentials ...string) error {
}
// Logout is reset session
func (s *Scraper) Logout() {
func (s *Scraper) Logout() error {
req, err := http.NewRequest("POST", logoutURL, nil)
if err != nil {
return err
}
err = s.RequestAPI(req, nil)
if err != nil {
return err
}
s.isLogged = false
s.guestToken = ""
s.client.Jar, _ = cookiejar.New(nil)
s.setBearerToken(bearerToken)
return nil
}
func (s *Scraper) GetCookies() []*http.Cookie {

View file

@ -22,13 +22,15 @@ func TestAuth(t *testing.T) {
t.Fatalf("Expected IsLoggedIn() = true")
}
cookies := scraper.GetCookies()
scraper.Logout()
if scraper.IsLoggedIn() {
t.Error("Expected IsLoggedIn() = false")
}
scraper2 := twitterscraper.New()
scraper2.SetCookies(cookies)
if !scraper2.IsLoggedIn() {
t.Error("Expected restored IsLoggedIn() = true")
}
if err := scraper.Logout(); err != nil {
t.Errorf("Logout() error = %v", err)
}
if scraper.IsLoggedIn() {
t.Error("Expected IsLoggedIn() = false")
}
}