/
login.go
49 lines (37 loc) · 1.04 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
package sdarot
import (
"errors"
"fmt"
"net/url"
"strings"
"github.com/PuerkitoBio/goquery"
)
var ErrInvalidCredentials = fmt.Errorf("InvalidCredentials")
func (client *Client) login(username string, password string) error {
initResponse, err := client.client.Get(SdarotURL)
if err != nil {
return errors.New("couldn't reach " + SdarotURL + ", the website might be down")
}
defer initResponse.Body.Close()
endpoint, _ := url.JoinPath(SdarotURL, "login")
params := url.Values{}
params.Set("username", username)
params.Set("password", password)
params.Set("location", "%2F")
params.Set("submit_login", "")
response, err := client.client.PostForm(endpoint, params)
if err != nil {
return fmt.Errorf("failed to login: %w", err)
}
defer response.Body.Close()
doc, err := goquery.NewDocumentFromReader(response.Body)
if err != nil {
return fmt.Errorf("got invalid HTML: %w", err)
}
s := doc.Find(`.alert`)
wrongCredsMsg := strings.TrimSpace(s.Text())
if wrongCredsMsg != "" {
return ErrInvalidCredentials
}
return nil
}