forked from imperatrona/twitter-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
512 lines (453 loc) · 12.5 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package twitterscraper
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"strings"
"time"
"math/rand"
)
const (
loginURL = "https://api.twitter.com/1.1/onboarding/task.json"
logoutURL = "https://api.twitter.com/1.1/account/logout.json"
oAuthURL = "https://api.twitter.com/oauth2/token"
// Doesn't require x-client-transaction-id header
bearerToken1 = "AAAAAAAAAAAAAAAAAAAAAG5LOQEAAAAAbEKsIYYIhrfOQqm4H8u7xcahRkU%3Dz98HKmzbeXdKqBfUDmElcqYl0cmmKY9KdS2UoNIz3Phapgsowi"
// Requires x-client-transaction-id header
bearerToken2 = "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
appConsumerKey = "3nVuSoBZnx6U4vzUxf5w"
appConsumerSecret = "Bcs59EFbbsdF6Sl9Ng71smgStWEGwXXKSjYvPVt7qys"
)
type (
OpenAccount struct {
OAuthToken string `json:"oauth_token"`
OAuthTokenSecret string `json:"oauth_token_secret"`
}
flow struct {
Errors []struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"errors"`
FlowToken string `json:"flow_token"`
Status string `json:"status"`
Subtasks []struct {
SubtaskID string `json:"subtask_id"`
OpenAccount OpenAccount `json:"open_account"`
} `json:"subtasks"`
}
verifyCredentials struct {
Errors []struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"errors"`
}
)
func (s *Scraper) getAccessToken(consumerKey, consumerSecret string) (string, error) {
req, err := http.NewRequest("POST", oAuthURL, strings.NewReader("grant_type=client_credentials"))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(consumerKey, consumerSecret)
res, err := s.client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
body, _ := io.ReadAll(res.Body)
return "", fmt.Errorf("unexpected status code: %d, body: %s", res.StatusCode, body)
}
var a struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(res.Body).Decode(&a); err != nil {
return "", err
}
return a.AccessToken, nil
}
func (s *Scraper) getFlow(data map[string]interface{}) (*flow, error) {
headers := http.Header{
"Authorization": []string{"Bearer " + s.bearerToken},
"Content-Type": []string{"application/json"},
"User-Agent": []string{s.userAgent},
"X-Guest-Token": []string{s.guestToken},
"X-Twitter-Auth-Type": []string{"OAuth2Client"},
"X-Twitter-Active-User": []string{"yes"},
"X-Twitter-Client-Language": []string{"en"},
}
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", loginURL, bytes.NewReader(jsonData))
if err != nil {
return nil, err
}
req.Header = headers
s.setCSRFToken(req)
resp, err := s.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var info flow
err = json.NewDecoder(resp.Body).Decode(&info)
if err != nil {
return nil, err
}
return &info, nil
}
func (s *Scraper) getFlowToken(data map[string]interface{}) (string, error) {
info, err := s.getFlow(data)
if err != nil {
return "", err
}
if len(info.Errors) > 0 {
return "", fmt.Errorf("auth error (%d): %v", info.Errors[0].Code, info.Errors[0].Message)
}
if len(info.Subtasks) > 0 {
if info.Subtasks[0].SubtaskID == "LoginEnterAlternateIdentifierSubtask" {
err = fmt.Errorf("auth error: %v", "LoginEnterAlternateIdentifierSubtask")
} else if info.Subtasks[0].SubtaskID == "LoginAcid" {
err = fmt.Errorf("auth error: %v", "LoginAcid")
} else if info.Subtasks[0].SubtaskID == "LoginTwoFactorAuthChallenge" {
err = fmt.Errorf("auth error: %v", "LoginTwoFactorAuthChallenge")
} else if info.Subtasks[0].SubtaskID == "DenyLoginSubtask" {
err = fmt.Errorf("auth error: %v", "DenyLoginSubtask")
}
}
return info.FlowToken, err
}
// IsLoggedIn check if scraper logged in
func (s *Scraper) IsLoggedIn() bool {
s.isLogged = true
s.setBearerToken(bearerToken1)
req, err := http.NewRequest("GET", "https://api.twitter.com/1.1/account/verify_credentials.json", nil)
if err != nil {
return false
}
var verify verifyCredentials
err = s.RequestAPI(req, &verify)
if err != nil || verify.Errors != nil {
s.isLogged = false
s.setBearerToken(bearerToken)
} else {
s.isLogged = true
}
return s.isLogged
}
// randomDelay introduces a random delay between 1 and 3 seconds
func randomDelay() {
delay := time.Duration(3000+rand.Intn(5000)) * time.Millisecond
time.Sleep(delay)
}
// Login to Twitter
// Use Login(username, password) for ordinary login
// or Login(username, password, email) for login if you have email confirmation
// or Login(username, password, code_for_2FA) for login if you have two-factor authentication
func (s *Scraper) Login(credentials ...string) error {
var username, password, confirmation string
if len(credentials) < 2 || len(credentials) > 3 {
return fmt.Errorf("invalid credentials")
}
username, password = credentials[0], credentials[1]
if len(credentials) == 3 {
confirmation = credentials[2]
}
s.setBearerToken(bearerToken2)
err := s.GetGuestToken()
if err != nil {
return err
}
randomDelay()
// flow start
data := map[string]interface{}{
"flow_name": "login",
"input_flow_data": map[string]interface{}{
"flow_context": map[string]interface{}{
"debug_overrides": map[string]interface{}{},
"start_location": map[string]interface{}{"location": "splash_screen"},
},
},
}
flowToken, err := s.getFlowToken(data)
if err != nil {
return err
}
randomDelay()
// flow instrumentation step
data = map[string]interface{}{
"flow_token": flowToken,
"subtask_inputs": []map[string]interface{}{
{
"subtask_id": "LoginJsInstrumentationSubtask",
"js_instrumentation": map[string]interface{}{"response": "{}", "link": "next_link"},
},
},
}
flowToken, err = s.getFlowToken(data)
if err != nil {
return err
}
randomDelay()
// flow username step
data = map[string]interface{}{
"flow_token": flowToken,
"subtask_inputs": []map[string]interface{}{
{
"subtask_id": "LoginEnterUserIdentifierSSO",
"settings_list": map[string]interface{}{
"setting_responses": []map[string]interface{}{
{
"key": "user_identifier",
"response_data": map[string]interface{}{"text_data": map[string]interface{}{"result": username}},
},
},
"link": "next_link",
},
},
},
}
flowToken, err = s.getFlowToken(data)
if err != nil {
return err
}
randomDelay()
// flow password step
data = map[string]interface{}{
"flow_token": flowToken,
"subtask_inputs": []map[string]interface{}{
{
"subtask_id": "LoginEnterPassword",
"enter_password": map[string]interface{}{"password": password, "link": "next_link"},
},
},
}
flowToken, err = s.getFlowToken(data)
if err != nil {
return err
}
randomDelay()
// flow duplication check
data = map[string]interface{}{
"flow_token": flowToken,
"subtask_inputs": []map[string]interface{}{
{
"subtask_id": "AccountDuplicationCheck",
"check_logged_in_account": map[string]interface{}{"link": "AccountDuplicationCheck_false"},
},
},
}
flowToken, err = s.getFlowToken(data)
if err != nil {
var confirmationSubtask string
for _, subtask := range []string{"LoginAcid", "LoginTwoFactorAuthChallenge"} {
if strings.Contains(err.Error(), subtask) {
confirmationSubtask = subtask
break
}
}
if confirmationSubtask != "" {
if confirmation == "" {
return fmt.Errorf("confirmation data required for %v", confirmationSubtask)
}
randomDelay()
// flow confirmation
data = map[string]interface{}{
"flow_token": flowToken,
"subtask_inputs": []map[string]interface{}{
{
"subtask_id": confirmationSubtask,
"enter_text": map[string]interface{}{"text": confirmation, "link": "next_link"},
},
},
}
_, err = s.getFlowToken(data)
if err != nil {
return err
}
} else {
return err
}
}
s.isLogged = true
s.isOpenAccount = false
return nil
}
// LoginOpenAccount as Twitter app
func (s *Scraper) LoginOpenAccount() (OpenAccount, error) {
accessToken, err := s.getAccessToken(appConsumerKey, appConsumerSecret)
if err != nil {
return OpenAccount{}, err
}
s.setBearerToken(accessToken)
err = s.GetGuestToken()
if err != nil {
return OpenAccount{}, err
}
// flow start
data := map[string]interface{}{
"flow_name": "welcome",
"input_flow_data": map[string]interface{}{
"flow_context": map[string]interface{}{
"debug_overrides": map[string]interface{}{},
"start_location": map[string]interface{}{"location": "splash_screen"},
},
},
}
flowToken, err := s.getFlowToken(data)
if err != nil {
return OpenAccount{}, err
}
// flow next link
data = map[string]interface{}{
"flow_token": flowToken,
"subtask_inputs": []interface{}{
map[string]interface{}{
"subtask_id": "NextTaskOpenLink",
},
},
}
info, err := s.getFlow(data)
if err != nil {
return OpenAccount{}, err
}
if len(info.Subtasks) > 0 {
if info.Subtasks[0].SubtaskID == "OpenAccount" {
s.oAuthToken = info.Subtasks[0].OpenAccount.OAuthToken
s.oAuthSecret = info.Subtasks[0].OpenAccount.OAuthTokenSecret
if s.oAuthToken == "" || s.oAuthSecret == "" {
return OpenAccount{}, fmt.Errorf("auth error: %v", "Token or Secret is empty")
}
s.isLogged = true
s.isOpenAccount = true
return OpenAccount{
OAuthToken: info.Subtasks[0].OpenAccount.OAuthToken,
OAuthTokenSecret: info.Subtasks[0].OpenAccount.OAuthTokenSecret,
}, nil
}
}
return OpenAccount{}, fmt.Errorf("auth error: %v", "OpenAccount")
}
func (s *Scraper) WithOpenAccount(openAccount OpenAccount) {
s.oAuthToken = openAccount.OAuthToken
s.oAuthSecret = openAccount.OAuthTokenSecret
s.isLogged = true
s.isOpenAccount = true
}
// Logout is reset session
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.isOpenAccount = false
s.guestToken = ""
s.oAuthToken = ""
s.oAuthSecret = ""
s.client.Jar, _ = cookiejar.New(nil)
s.setBearerToken(bearerToken)
return nil
}
func (s *Scraper) GetCookies() []*http.Cookie {
var cookies []*http.Cookie
for _, cookie := range s.client.Jar.Cookies(twURL) {
if strings.Contains(cookie.Name, "guest") {
continue
}
cookie.Domain = twURL.Host
cookies = append(cookies, cookie)
}
return cookies
}
func (s *Scraper) SetCookies(cookies []*http.Cookie) {
s.client.Jar.SetCookies(twURL, cookies)
}
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(token AuthToken) {
expires := time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)
cookies := []*http.Cookie{{
Name: "auth_token",
Value: token.Token,
Path: "",
Domain: "twitter.com",
Expires: expires,
RawExpires: "",
MaxAge: 0,
Secure: false,
HttpOnly: false,
SameSite: 0,
Raw: "",
Unparsed: nil,
}, {
Name: "ct0",
Value: token.CSRFToken,
Path: "",
Domain: "twitter.com",
Expires: expires,
RawExpires: "",
MaxAge: 0,
Secure: false,
HttpOnly: false,
SameSite: 0,
Raw: "",
Unparsed: nil,
}}
s.SetCookies(cookies)
}
func (s *Scraper) sign(method string, ref *url.URL) string {
m := make(map[string]string)
m["oauth_consumer_key"] = appConsumerKey
m["oauth_nonce"] = "0"
m["oauth_signature_method"] = "HMAC-SHA1"
m["oauth_timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
m["oauth_token"] = s.oAuthToken
key := []byte(appConsumerSecret + "&" + s.oAuthSecret)
h := hmac.New(sha1.New, key)
query := ref.Query()
for k, v := range m {
query.Set(k, v)
}
req := []string{method, ref.Scheme + "://" + ref.Host + ref.Path, query.Encode()}
var reqBuf bytes.Buffer
for _, value := range req {
if reqBuf.Len() > 0 {
reqBuf.WriteByte('&')
}
reqBuf.WriteString(url.QueryEscape(value))
}
h.Write(reqBuf.Bytes())
m["oauth_signature"] = base64.StdEncoding.EncodeToString(h.Sum(nil))
var b bytes.Buffer
for k, v := range m {
if b.Len() > 0 {
b.WriteByte(',')
}
b.WriteString(k)
b.WriteByte('=')
b.WriteString(url.QueryEscape(v))
}
return "OAuth " + b.String()
}