-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
126 lines (99 loc) · 2.27 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package spacetrack
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/shibingli/spacetrack/utils"
)
type Auth struct {
Username string `json:"identity" xml:"identity"`
Password string `json:"password" xml:"password"`
Cookies []*http.Cookie `json:"cookies" xml:"cookies"`
}
func (s *SpaceTrack) jsonAuthInfo() ([]byte, error) {
sta := &Auth{
Username: s.Auth.Username,
Password: s.Auth.Password,
}
return json.Marshal(sta)
}
func (s *SpaceTrack) Login() (*SpaceTrack, error) {
authInfo, err := s.jsonAuthInfo()
if err != nil {
return nil, err
}
authInfo = bytes.TrimSpace(authInfo)
loginUrl := strings.TrimSpace(DefaultLoginURL)
if loginUrl == "" || len(authInfo) == 0 {
return nil, fmt.Errorf("%s", utils.ErrorInvalidParameter)
}
loginUrl = utils.JoinURLPath(DefaultBaseURL, DefaultLoginURL)
headers := map[string]interface{}{"Content-Type": "application/json"}
resp, err := utils.NewHttpClient(
http.MethodPost, loginUrl,
bytes.NewReader(authInfo),
&utils.HttpClientOpts{
DisableCompression: true,
DisableKeepAlives: true,
Headers: headers,
},
)
if err != nil {
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return nil, fmt.Errorf(
utils.HttpResultFormat,
resp.StatusCode,
string(body),
)
}
s.Auth.Cookies = resp.Cookies()
return s, nil
}
func (s *SpaceTrack) Logout() (err error) {
logoutUrl := strings.TrimSpace(DefaultLogoutURL)
if logoutUrl == "" {
return fmt.Errorf("%s", utils.ErrorInvalidParameter)
}
logoutUrl = utils.JoinURLPath(DefaultBaseURL, DefaultLogoutURL)
headers := map[string]interface{}{"Content-Type": "application/json"}
resp, err := utils.NewHttpClient(
http.MethodPost,
logoutUrl,
nil,
&utils.HttpClientOpts{
DisableCompression: true,
DisableKeepAlives: true,
Headers: headers,
},
)
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf(
utils.HttpResultFormat,
resp.StatusCode,
string(body),
)
}
return nil
}