master
go 70 lines 1.3 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package pihole
4
5 import (
6 "encoding/json"
7 "fmt"
8 "net/http"
9
10 "github.com/netdata/netdata/go/plugins/pkg/web"
11 )
12
13 func (c *Collector) checkAuthSession() error {
14 if c.auth == nil {
15 return nil
16 }
17
18 req, err := web.NewHTTPRequestWithPath(c.RequestConfig, urlPathAPIAuth)
19 if err != nil {
20 return err
21 }
22 req.Header.Set("X-FTL-SID", c.auth.Session.Sid)
23 req.Header.Set("X-FTL-CSRF", c.auth.Session.Csrf)
24
25 var resp ftlAPIAuthResponse
26
27 if err := web.DoHTTP(c.httpClient).RequestJSON(req, &resp); err != nil {
28 if web.IsStatusCode(err, 401) {
29 c.auth = nil
30 return nil
31 }
32 return err
33 }
34
35 if !resp.Session.Valid {
36 c.auth = nil
37 return nil
38 }
39
40 return nil
41 }
42
43 func (c *Collector) getAuthSession() (*ftlAPIAuthResponse, error) {
44 var pass struct {
45 Password string `json:"password"`
46 }
47 pass.Password = c.Password
48 bs, _ := json.Marshal(pass)
49
50 cfg := c.RequestConfig.Copy()
51 cfg.Method = http.MethodPost
52 cfg.Body = string(bs)
53
54 req, err := web.NewHTTPRequestWithPath(cfg, urlPathAPIAuth)
55 if err != nil {
56 return nil, err
57 }
58
59 var resp ftlAPIAuthResponse
60
61 if err := web.DoHTTP(c.httpClient).RequestJSON(req, &resp); err != nil {
62 return nil, err
63 }
64
65 if !resp.Session.Valid {
66 return nil, fmt.Errorf("invalid auth session (%s)", resp.Session.Message)
67 }
68
69 return &resp, nil
70 }