github.com/esnet/gdg@v0.6.1-0.20240412190737-6b6eba9c14d8/internal/service/login.go (about)

     1  package service
     2  
     3  import (
     4  	"crypto/tls"
     5  	"github.com/esnet/gdg/internal/api"
     6  	"github.com/esnet/gdg/internal/config"
     7  	"github.com/go-openapi/strfmt"
     8  	"log"
     9  	"log/slog"
    10  	"net/http"
    11  	"net/url"
    12  
    13  	"github.com/grafana/grafana-openapi-client-go/client"
    14  )
    15  
    16  // Login sets admin flag and provisions the Extended API for calls unsupported by the OpenAPI spec.
    17  func (s *DashNGoImpl) Login() {
    18  	var err error
    19  	// Will only succeed for BasicAuth
    20  	userInfo, err := s.GetUserInfo()
    21  	// Sets state based on user permissions
    22  	if err == nil {
    23  		s.grafanaConf.SetGrafanaAdmin(userInfo.IsGrafanaAdmin)
    24  	}
    25  
    26  	s.extended = api.NewExtendedApi()
    27  }
    28  
    29  func ignoreSSL(transportConfig *client.TransportConfig) {
    30  	_, clientTransport := ignoreSSLErrors()
    31  	transportConfig.TLSConfig = clientTransport.TLSClientConfig
    32  }
    33  
    34  type NewClientOpts func(transportConfig *client.TransportConfig)
    35  
    36  func (s *DashNGoImpl) getNewClient(opts ...NewClientOpts) (*client.GrafanaHTTPAPI, *client.TransportConfig) {
    37  	var err error
    38  	u, err := url.Parse(s.grafanaConf.URL)
    39  	if err != nil {
    40  		log.Fatal("invalid Grafana URL", s.grafanaConf.URL)
    41  	}
    42  	path, err := url.JoinPath(u.Path, "api")
    43  	if err != nil {
    44  		log.Fatal("invalid Grafana URL Path")
    45  	}
    46  
    47  	httpConfig := &client.TransportConfig{
    48  		Host:         u.Host,
    49  		BasePath:     path,
    50  		Schemes:      []string{u.Scheme},
    51  		NumRetries:   config.Config().GetGDGConfig().GetAppGlobals().RetryCount,
    52  		RetryTimeout: config.Config().GetGDGConfig().GetAppGlobals().GetRetryTimeout(),
    53  	}
    54  
    55  	if s.grafanaConf.OrganizationName != "" {
    56  		orgId, err := api.NewExtendedApi().GetConfiguredOrgId(s.grafanaConf.OrganizationName)
    57  		if err != nil {
    58  			slog.Error("unable to determine org ID, falling back", slog.Any("err", err))
    59  			orgId = 1
    60  		}
    61  		opts = append(opts, func(clientCfg *client.TransportConfig) {
    62  			clientCfg.OrgID = orgId
    63  		})
    64  	} else {
    65  		opts = append(opts, func(clientCfg *client.TransportConfig) {
    66  			clientCfg.OrgID = config.DefaultOrganizationId
    67  		})
    68  	}
    69  	for _, opt := range opts {
    70  		if opt != nil {
    71  			opt(httpConfig)
    72  		}
    73  	}
    74  	if config.Config().IgnoreSSL() {
    75  		ignoreSSL(httpConfig)
    76  	}
    77  
    78  	return client.NewHTTPClientWithConfig(strfmt.Default, httpConfig), httpConfig
    79  }
    80  
    81  // GetClient Returns a new defaultClient given token precedence over Basic Auth
    82  func (s *DashNGoImpl) GetClient() *client.GrafanaHTTPAPI {
    83  	if s.grafanaConf.APIToken != "" {
    84  		grafanaClient, _ := s.getNewClient(func(clientCfg *client.TransportConfig) {
    85  			clientCfg.APIKey = s.grafanaConf.APIToken
    86  		})
    87  		return grafanaClient
    88  	} else {
    89  		return s.GetBasicAuthClient()
    90  	}
    91  }
    92  
    93  // GetAdminClient Returns the admin defaultClient if one is configured
    94  func (s *DashNGoImpl) GetAdminClient() *client.GrafanaHTTPAPI {
    95  	if !s.grafanaConf.IsGrafanaAdmin() || s.grafanaConf.UserName == "" {
    96  		log.Fatal("Unable to get Grafana Admin SecureData. ")
    97  	}
    98  	return s.GetBasicAuthClient()
    99  }
   100  
   101  // GetBasicAuthClient returns a basic auth grafana API Client
   102  func (s *DashNGoImpl) GetBasicAuthClient() *client.GrafanaHTTPAPI {
   103  	grafanaClient, _ := s.getNewClient(func(clientCfg *client.TransportConfig) {
   104  		clientCfg.BasicAuth = url.UserPassword(s.grafanaConf.UserName, s.grafanaConf.Password)
   105  	})
   106  	return grafanaClient
   107  }
   108  
   109  // ignoreSSLErrors when called replaces the default http legacyClient to ignore invalid SSL issues.
   110  // only to be used for testing, highly discouraged in production.
   111  func ignoreSSLErrors() (*http.Client, *http.Transport) {
   112  	customTransport := http.DefaultTransport.(*http.Transport).Clone()
   113  	customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
   114  	httpclient := &http.Client{Transport: customTransport}
   115  	return httpclient, customTransport
   116  }