Fix FetchSessionKey

This commit is contained in:
Kalle Carlbark 2021-11-27 13:24:15 +01:00
parent b054d32835
commit 47dc036112
No known key found for this signature in database

View file

@ -7,7 +7,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
@ -184,59 +183,37 @@ func (c *Client) SetToken(token string) {
} }
// FetchSessionKey fetches sessionkey // FetchSessionKey fetches sessionkey
func (n *Client) FetchSessionKey(privatekey string) error { func (c *Client) FetchSessionKey(privatekey string) error {
form := url.Values{} form := url.Values{}
form.Add("private_key", privatekey) form.Add("private_key", privatekey)
query := form.Encode() query := form.Encode()
transport := &http.Transport{ ctx := context.Background()
// #nosec XXX: FIXIT req, err := c.newRequest(ctx, "POST", secretsPath+"/get-session-key/", "", strings.NewReader(query))
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))
if err != nil { if err != nil {
return err return err
} }
request.Header.Add("Accept", "application/json") req.Header.Add("Accept", "application/json")
request.Header.Add("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
if n.FetchMode != "" { if c.FetchMode != "" {
request.Header.Add("js.fetch:mode", "no-cors") req.Header.Add("js.fetch:mode", "no-cors")
} }
request.Header.Add("Authorization", " Token "+n.Token) req.Header.Add("Authorization", " Token "+c.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
}
var sessionkey NetBoxSessionKey var sessionkey NetBoxSessionKey
err = json.Unmarshal(data, &sessionkey) res, err := c.do(req, sessionkey)
if err != nil { if err != nil {
return err 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 return nil
} }