terraform-provider-gitea/gitea/config.go

82 lines
1.9 KiB
Go
Raw Normal View History

2022-03-31 21:24:00 +00:00
package gitea
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
"time"
2022-03-31 21:24:00 +00:00
"code.gitea.io/sdk/gitea"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging"
2022-03-31 21:24:00 +00:00
)
// Config is per-provider, specifies where to connect to gitea
type Config struct {
Token string
Username string
Password string
BaseURL string
Insecure bool
CACertFile string
}
// Client returns a *gitea.Client to interact with the configured gitea instance
func (c *Config) Client() (interface{}, error) {
if c.Token == "" && c.Username == "" {
return nil, fmt.Errorf("either a token or a username needs to be used")
}
// Configure TLS/SSL
var tlsConfig tls.Config
2022-03-31 21:24:00 +00:00
// If a CACertFile has been specified, use that for cert validation
if c.CACertFile != "" {
caCert, err := ioutil.ReadFile(c.CACertFile)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
}
// If configured as insecure, turn off SSL verification
tlsConfig.InsecureSkipVerify = c.Insecure
2022-03-31 21:24:00 +00:00
t := http.DefaultTransport.(*http.Transport).Clone()
t.TLSClientConfig = &tlsConfig
2022-03-31 21:24:00 +00:00
t.MaxIdleConnsPerHost = 100
t.TLSHandshakeTimeout = 10 * time.Second
2022-03-31 21:24:00 +00:00
httpClient := &http.Client{
Transport: logging.NewTransport("Gitea", t),
}
if c.BaseURL == "" {
c.BaseURL = "https://gitea.com"
}
2022-03-31 23:19:14 +00:00
var client *gitea.Client
var err error
2022-03-31 23:19:14 +00:00
if c.Token != "" {
client, err = gitea.NewClient(c.BaseURL, gitea.SetToken(c.Token), gitea.SetHTTPClient(httpClient))
if err != nil {
return nil, err
}
2022-03-31 23:19:14 +00:00
}
2022-03-31 21:24:00 +00:00
if c.Username != "" {
client, err = gitea.NewClient(c.BaseURL, gitea.SetBasicAuth(c.Username, c.Password), gitea.SetHTTPClient(httpClient))
if err != nil {
return nil, err
}
2022-03-31 21:24:00 +00:00
}
// Test the credentials by checking we can get information about the authenticated user.
_, _, err = client.GetMyUserInfo()
2022-03-31 21:24:00 +00:00
return client, err
}