-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_client.go
298 lines (245 loc) · 5.84 KB
/
auth_client.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package go_fritzbox_api
/*
*
* The MIT License (MIT)
* Copyright (c) 2015 Philipp Franke
*
* Modified by ByteSizedMarius (2022)
*
*/
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
)
type Client struct {
BaseUrl string
Username string
Password string
session *session
urlO *url.URL
client *http.Client
}
func (c *Client) Copy() *Client {
nc := Client{
BaseUrl: c.BaseUrl,
Username: c.Username,
Password: c.Password,
}
return &nc
}
func (c *Client) SetCustomHTTPClient(client *http.Client) {
c.client = client
}
func (c *Client) Initialize() error {
if c.IsInitialized() {
c.Close()
}
// set default base url
if c.BaseUrl == "" {
c.BaseUrl = "http://192.168.178.1/"
}
// check url validity
if !strings.HasPrefix(c.BaseUrl, "http") {
return fmt.Errorf("base url has to start with http(s)://")
}
// convert url
fu, err := url.Parse(c.BaseUrl)
if err != nil {
return err
}
c.urlO = fu
// set http client
if c.client == nil {
c.client = http.DefaultClient
}
// authenticate
return c.auth(c.Username, c.Password)
}
func (c *Client) SID() string {
return c.session.Sid
}
func (c *Client) Close() {
if c.IsInitialized() {
if c.session != nil {
c.session.close()
}
c.client.CloseIdleConnections()
c.client = nil
c.session = nil
}
}
// CustomRequest allows one to send a custom request. The method can be http.MethodPost or http.MethodGet.
// The urlPath should always only be the path (for example "data.lua"), get-queries are set via the data-field. See examples.
func (c *Client) CustomRequest(method string, urlPath string, data url.Values) (statusCode int, body string, err error) {
resp, err := c.doRequest(method, urlPath, data, true)
if err != nil {
return
}
body, err = getBody(resp)
statusCode = resp.StatusCode
return
}
//
//
// client
//
//
func (c *Client) requestAndDecode(method string, urlStr string, data url.Values, mystruct interface{}, checkExpiry bool) (err error) {
resp, err := c.doRequest(method, urlStr, data, checkExpiry)
if err != nil {
return err
}
return decode(resp, mystruct)
}
func (c *Client) doRequest(method string, urlStr string, data url.Values, checkExpiry bool) (resp *http.Response, err error) {
// refresh session potentially
if checkExpiry {
if err = c.checkExpiry(); err != nil {
return
}
}
// build request url
u, err := c.resolveUrl(urlStr)
if err != nil {
return
}
// if POST request, encode body accordingly
var buf io.Reader = nil
if method == http.MethodPost {
buf = strings.NewReader(data.Encode())
}
// create request
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept-Encoding", "gzip, deflate")
// if GET, add query to url
if method == http.MethodGet {
q := req.URL.Query()
for k, e := range data {
q.Add(k, e[0])
}
req.URL.RawQuery = q.Encode()
}
// send request
resp, err = c.client.Do(req)
if err != nil {
return nil, err
}
if sc := resp.StatusCode; sc < 200 || sc > 299 {
return nil, fmt.Errorf("invalid statuscode (%v)", resp.StatusCode)
}
return resp, nil
}
func (c *Client) resolveUrl(urlStr string) (u *url.URL, err error) {
// build reqest
rel, err := url.Parse(urlStr)
if err != nil {
return
}
return c.urlO.ResolveReference(rel), nil
}
func (c *Client) get(urlStr string) (req *http.Request, err error) {
u, err := c.resolveUrl(urlStr)
if err != nil {
return
}
if c.session != nil {
if c.session.Sid != DefaultSid {
values := u.Query()
values.Set("sid", c.session.Sid)
u.RawQuery = values.Encode()
}
}
req, err = http.NewRequest("GET", u.String(), nil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept-Encoding", "gzip, deflate")
if err != nil {
return nil, err
}
return req, nil
}
func (c *Client) IsInitialized() bool {
return c.client != nil
}
func (c *Client) checkExpiry() (err error) {
if (c.IsInitialized() && c.session.isExpired()) || !c.IsInitialized() {
err = c.Initialize()
}
return
}
func (c *Client) String() string {
return c.session.String()
}
// auth sends an auth request and returns an error, if any. session is stored
// in Client in order to perform requests with authentication.
func (c *Client) auth(username, password string) error {
var s *session
if c.session == nil {
s = newSession(c)
c.session = s
} else {
s = c.session
}
if err := s.open(); err != nil {
return err
}
if err := s.auth(username, password); err != nil {
return err
}
return nil
}
//
//
// Helper
//
//
func decode(resp *http.Response, mystruct interface{}) (err error) {
if strings.Contains(resp.Header.Get("Content-Type"), "text/xml") {
err = xml.NewDecoder(resp.Body).Decode(mystruct)
} else if strings.Contains(resp.Header.Get("Content-Type"), "application/json") {
err = json.NewDecoder(resp.Body).Decode(mystruct)
}
return
}
func getBody(resp *http.Response) (body string, err error) {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return
}
return strings.Trim(string(bodyBytes), "\n"), nil
}
func getUntil(main string, split string) string {
return main[:strings.Index(main, split)]
}
func getFrom(main string, split string) string {
return main[strings.Index(main, split):]
}
func getFromOffset(main string, split string, offset int) string {
return main[strings.Index(main, split)+offset:]
}
func valueFromJson(body string, keys []string) (v map[string]interface{}, err error) {
err = json.Unmarshal([]byte(body), &v)
if err != nil {
var e *json.SyntaxError
if errors.As(err, &e) {
log.Printf("syntax error at byte offset %d", e.Offset)
}
return
}
var r map[string]interface{}
r = v[keys[0]].(map[string]interface{})
for i := 1; i < len(keys); i++ {
r = r[keys[i]].(map[string]interface{})
}
return r, nil
}