-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
46 lines (42 loc) · 1.14 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
package arctic
import (
"errors"
"github.com/ArcticOJ/go-api-bindings/v0/types"
"github.com/ArcticOJ/go-api-bindings/v0/types/common"
"github.com/ArcticOJ/go-api-bindings/v0/types/common/auth"
"net/http"
"slices"
"strings"
)
func (c *Client) IsAuthenticated() bool {
return slices.ContainsFunc(c.c.Cookies, func(cookie *http.Cookie) bool {
return cookie.Name == "session" && strings.TrimSpace(cookie.Value) != ""
})
}
func (c *Client) Auth(cookie *http.Cookie) {
c.c.SetCommonCookies(cookie)
}
func (c *Client) Login(handle string, password string, remember bool) (*http.Cookie, error) {
var err common.Error
res, e := c.c.R().
SetErrorResult(&err).
SetBody(auth.LoginForm{
Handle: handle,
Password: password,
RememberMe: remember,
}).
Post("/auth/login")
if e != nil {
return nil, e
}
if err.Code >= http.StatusBadRequest {
return nil, errors.New(err.Message)
}
cookie := slices.IndexFunc(res.Cookies(), func(cookie *http.Cookie) bool {
return cookie.Name == "session" && strings.TrimSpace(cookie.Value) != ""
})
if cookie == -1 {
return nil, types.ErrInvalidCookie
}
return res.Cookies()[cookie], nil
}