Add secrets.

This commit is contained in:
Kalle Carlbark 2019-12-17 16:35:52 +01:00
parent 3c7c83f3cf
commit 24a126895f
No known key found for this signature in database
GPG key ID: 3FC0C93C5A5A0670
2 changed files with 68 additions and 0 deletions

View file

@ -1,15 +1,82 @@
package netboxgo
import (
"crypto/tls"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
)
// NetBox settings struct
type NetBox struct {
RootURL string
Token string
SessionKey string
InsecureSkipVerify bool
}
type NetBoxSessionKey struct {
XSessionKey string `json:"session_key"`
}
// New populates the NetBox settings struct
func (n *NetBox) New(root, token string, TLSSkipVerify bool) {
n.RootURL = root
n.Token = token
n.InsecureSkipVerify = TLSSkipVerify
}
func (n *NetBox) FetchSessionKey(privatekey string) error {
form := url.Values{}
form.Add("private_key", privatekey)
query := form.Encode()
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: n.InsecureSkipVerify},
}
timeout := time.Duration(60 * time.Second)
client := &http.Client{
Timeout: timeout,
Transport: transport,
}
request, err := http.NewRequest("POST", n.RootURL+"/api/secrets/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")
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("Error: 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
err = json.Unmarshal(data, &sessionkey)
if err != nil {
return err
}
n.SessionKey = sessionkey.XSessionKey
return nil
}

View file

@ -85,6 +85,7 @@ func (n *NetBox) ListSecrets(i *SecretsList, f *SecretFilter) error {
}
request.Header.Add("Accept", "application/json")
request.Header.Add("Authorization", " Token "+n.Token)
request.Header.Add("X-Session-Key", n.SessionKey)
response, err := client.Do(request)
if err != nil {
return err