-
Notifications
You must be signed in to change notification settings - Fork 10
/
config.go
99 lines (87 loc) · 2.09 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package appgate
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"time"
"github.com/appgate/sdp-api-client-go/api/v14/openapi"
"github.com/google/uuid"
)
const (
// DefaultDescription is the default string for terraform resources.
DefaultDescription = "Managed by terraform"
)
// Config for appgate provider.
type Config struct {
URL string
Username string
Password string
Provider string
Insecure bool
Timeout int
Debug bool
Version int
}
// Client is the appgate API client.
type Client struct {
Token string
UUID string
API *openapi.APIClient
}
// Client creates
func (c *Config) Client() (*Client, error) {
timeoutDuration := time.Duration(c.Timeout)
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: c.Insecure,
},
Dial: (&net.Dialer{
Timeout: timeoutDuration * time.Second,
}).Dial,
TLSHandshakeTimeout: timeoutDuration * time.Second,
}
httpclient := &http.Client{
Transport: tr,
Timeout: ((timeoutDuration * 2) * time.Second),
}
clientCfg := &openapi.Configuration{
DefaultHeader: map[string]string{
"Accept": fmt.Sprintf("application/vnd.appgate.peer-v%d+json", c.Version),
},
UserAgent: "Appgate-TerraformProvider/1.0.0/go",
Debug: c.Debug,
Servers: []openapi.ServerConfiguration{
{
URL: c.URL,
},
},
HTTPClient: httpclient,
}
apiClient := openapi.NewAPIClient(clientCfg)
token, err := getToken(apiClient, c)
if err != nil {
return nil, err
}
client := &Client{
API: apiClient,
Token: token,
}
return client, nil
}
func getToken(apiClient *openapi.APIClient, cfg *Config) (string, error) {
ctx := context.Background()
// Login first, save token
loginOpts := openapi.LoginRequest{
ProviderName: cfg.Provider,
Username: openapi.PtrString(cfg.Username),
Password: openapi.PtrString(cfg.Password),
DeviceId: uuid.New().String(),
}
loginResponse, _, err := apiClient.LoginApi.LoginPost(ctx).LoginRequest(loginOpts).Execute()
if err != nil {
return "", prettyPrintAPIError(err)
}
return fmt.Sprintf("Bearer %s", *openapi.PtrString(*loginResponse.Token)), nil
}