-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
71 lines (61 loc) · 1.59 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
package trading212
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/PuerkitoBio/goquery"
)
// Login as a user obtaining the session cookies required to make other
// requests.
func (c *Client) Login(username, password string) error {
token, err := c.getAuthToken()
if err != nil {
return fmt.Errorf("get auth token: %w", err)
}
reqURL := "https://www.trading212.com/en/authenticate"
vs := url.Values{
"login[username]": {username},
"login[password]": {password},
"login[_token]": {token},
"login[rememberMe]": {"1"},
}
req, err := http.NewRequest(http.MethodPost, reqURL, strings.NewReader(vs.Encode()))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
resp, err := c.c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close() // nolint: errcheck
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("%d: %s", resp.StatusCode, string(body))
}
return nil
}
func (c *Client) getAuthToken() (string, error) {
loginURL := "https://www.trading212.com/en/login"
req, err := http.NewRequest(http.MethodGet, loginURL, nil)
if err != nil {
return "", err
}
resp, err := c.c.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close() // nolint: errcheck
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return "", fmt.Errorf("parse doc: %w", err)
}
token, ok := doc.Find(`input[name="login[_token]"]`).Attr("value")
if !ok {
return "", errors.New("login _token not found")
}
return token, nil
}