-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
66 lines (47 loc) · 1.18 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
package jschan
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
)
type PostLoginOptions struct {
Username string
Password string
Twofactor string
}
func (c *Client) Login(ctx context.Context, options *PostLoginOptions) error {
formData := url.Values{}
formData.Set("username", options.Username)
formData.Set("password", options.Password)
formData.Set("twofactor", options.Twofactor)
endodedBody := strings.NewReader(formData.Encode())
url := fmt.Sprintf("%s/forms/login", c.BaseURL)
req, err := http.NewRequest(http.MethodPost, url, endodedBody)
if err != nil {
return err
}
req = req.WithContext(ctx)
if err := c.sendRequest(req, nil, nil); err != nil {
return err
}
return nil
}
type GetCSRFTokenResponse struct {
Token string `json:"token"`
}
func (c *Client) GetCSRFToken(ctx context.Context) (*GetCSRFTokenResponse, error) {
url := fmt.Sprintf("%s/csrf.json", c.BaseURL)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
res := &GetCSRFTokenResponse{}
if err := c.sendRequest(req, &res, nil); err != nil {
return nil, err
}
c.CsrfToken = res.Token
return res, nil
}