forked from xalanq/cf-tool
-
Notifications
You must be signed in to change notification settings - Fork 7
/
login.go
100 lines (86 loc) · 1.94 KB
/
login.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
package client
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"github.com/fatih/color"
"github.com/xalanq/cf-tool/cookiejar"
"github.com/xalanq/cf-tool/util"
)
// genFtaa generate a random one
func genFtaa() string {
return util.RandString(18)
}
// genBfaa generate a bfaa
func genBfaa() string {
return "f1b3f18c715565b589b7823cda7448ce"
}
// ErrorNotLogged not logged in
var ErrorNotLogged = "Not logged in"
// checkLogin if login return nil
func checkLogin(username string, body []byte) error {
match, err := regexp.Match(fmt.Sprintf(`handle = "%v"`, username), body)
if err != nil || !match {
return errors.New(ErrorNotLogged)
}
return nil
}
func findCsrf(body []byte) (string, error) {
reg := regexp.MustCompile(`csrf='(.+?)'`)
tmp := reg.FindSubmatch(body)
if len(tmp) < 2 {
return "", errors.New("Cannot find csrf")
}
return string(tmp[1]), nil
}
// Login codeforces with username(handler) and password
func (c *Client) Login(username, password string) (err error) {
jar, _ := cookiejar.New(nil)
color.Cyan("Login %v...\n", username)
client := &http.Client{Jar: jar}
resp, err := client.Get("https://codeforces.com/enter")
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
csrf, err := findCsrf(body)
if err != nil {
return
}
ftaa := genFtaa()
bfaa := genBfaa()
resp, err = client.PostForm("https://codeforces.com/enter", url.Values{
"csrf_token": {csrf},
"action": {"enter"},
"ftaa": {ftaa},
"bfaa": {bfaa},
"handleOrEmail": {username},
"password": {password},
"_tta": {"176"},
})
if err != nil {
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
err = checkLogin(username, body)
if err != nil {
return
}
c.Jar = jar
c.Ftaa = ftaa
c.Bfaa = bfaa
c.Username = username
color.Green("Succeed!!")
return c.save()
}