From 47dc0361123834e19b941d3ab8ec8bbd4ca0a7c6 Mon Sep 17 00:00:00 2001 From: Kalle Carlbark Date: Sat, 27 Nov 2021 13:24:15 +0100 Subject: [PATCH] Fix FetchSessionKey --- netbox.go | 53 +++++++++++++++-------------------------------------- 1 file changed, 15 insertions(+), 38 deletions(-) diff --git a/netbox.go b/netbox.go index 7d79744..241aa26 100644 --- a/netbox.go +++ b/netbox.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "log" "net/http" "net/url" @@ -184,59 +183,37 @@ func (c *Client) SetToken(token string) { } // FetchSessionKey fetches sessionkey -func (n *Client) FetchSessionKey(privatekey string) error { +func (c *Client) FetchSessionKey(privatekey string) error { form := url.Values{} form.Add("private_key", privatekey) query := form.Encode() - transport := &http.Transport{ - // #nosec XXX: FIXIT - TLSClientConfig: &tls.Config{InsecureSkipVerify: n.InsecureSkipVerify}, - } - timeout := time.Duration(60 * time.Second) - client := &http.Client{ - Timeout: timeout, - Transport: transport, - } - const secretsPath = "/secrets" - request, err := http.NewRequest("POST", secretsPath+"/get-session-key/", strings.NewReader(query)) + ctx := context.Background() + req, err := c.newRequest(ctx, "POST", secretsPath+"/get-session-key/", "", strings.NewReader(query)) if err != nil { return err } - request.Header.Add("Accept", "application/json") - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") + req.Header.Add("Accept", "application/json") + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - if n.FetchMode != "" { - request.Header.Add("js.fetch:mode", "no-cors") + if c.FetchMode != "" { + req.Header.Add("js.fetch:mode", "no-cors") } - request.Header.Add("Authorization", " Token "+n.Token) - response, err := client.Do(request) - if err != nil { - return err - } - - if response.StatusCode != http.StatusOK { - return errors.Errorf("response was: %d should be %d\n%s\n", response.StatusCode, http.StatusOK, response.Header) - } - - data, err := ioutil.ReadAll(response.Body) - if err != nil { - return err - } - - err = response.Body.Close() - if err != nil { - return err - } + req.Header.Add("Authorization", " Token "+c.Token) var sessionkey NetBoxSessionKey - err = json.Unmarshal(data, &sessionkey) + res, err := c.do(req, sessionkey) if err != nil { return err } - n.SessionKey = sessionkey.XSessionKey + + if res.StatusCode != http.StatusOK { + return errors.Errorf("response was: %d should be %d\n%s\n", res.StatusCode, http.StatusOK, res.Header) + } + + c.SessionKey = sessionkey.XSessionKey return nil }