-
Notifications
You must be signed in to change notification settings - Fork 1
/
login.go
52 lines (41 loc) · 1.12 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
package gobgg
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
const loginPath = "login/api/v1"
// Login tries to login into the bgg using the credentials and returns the cookies required for next calls
func (bgg *BGG) Login(ctx context.Context, username, password string) error {
payload := map[string]interface{}{
"credentials": map[string]string{
"username": username,
"password": password,
},
}
b, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("failed to create the payload: %w", err)
}
u := bgg.buildURL(loginPath, nil)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewBuffer(b))
if err != nil {
return fmt.Errorf("failed to create the request: %w", err)
}
req.Header.Add("content-type", "application/json")
resp, err := bgg.do(req)
if err != nil {
return fmt.Errorf("http call failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 && resp.StatusCode >= 300 {
return fmt.Errorf("maybe, invalid username/password")
}
bgg.lock.Lock()
defer bgg.lock.Unlock()
bgg.cookies = resp.Cookies()
bgg.username = username
return nil
}