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"
"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
}