github.com/taubyte/tau-cli@v0.1.13-0.20240326000942-487f0d57edfc/singletons/auth_client/client.go (about) 1 package authClient 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 8 "github.com/taubyte/tau-cli/common" 9 "github.com/taubyte/tau-cli/constants" 10 "github.com/taubyte/tau-cli/env" 11 "github.com/taubyte/tau-cli/i18n" 12 networkI18n "github.com/taubyte/tau-cli/i18n/network" 13 singletonsI18n "github.com/taubyte/tau-cli/i18n/singletons" 14 loginLib "github.com/taubyte/tau-cli/lib/login" 15 "github.com/taubyte/tau-cli/singletons/config" 16 "github.com/taubyte/tau-cli/singletons/dreamland" 17 "github.com/taubyte/tau-cli/singletons/session" 18 "github.com/taubyte/tau-cli/states" 19 "github.com/taubyte/tau/clients/http" 20 client "github.com/taubyte/tau/clients/http/auth" 21 ) 22 23 var _client *client.Client 24 25 func Clear() { 26 _client = nil 27 } 28 29 func getClientUrl() (url string, err error) { 30 profile, err := loginLib.GetSelectedProfile() 31 if err != nil { 32 return "", err 33 } 34 35 switch profile.NetworkType { 36 case common.DreamlandNetwork: 37 port, err := dreamland.HTTPPort(context.TODO(), "auth") 38 if err != nil { 39 return "", err 40 } 41 url = fmt.Sprintf("http://localhost:%d", port) 42 case common.RemoteNetwork: 43 url = fmt.Sprintf("https://auth.tau.%s", profile.Network) 44 case common.PythonTestNetwork: 45 url = os.Getenv(constants.AuthURLEnvVarName) 46 if url == "" { 47 url = constants.ClientURL 48 } 49 default: 50 err = networkI18n.ErrorUnknownNetwork(profile.NetworkType) 51 } 52 53 return 54 } 55 56 func loadClient() (config.Profile, *client.Client, error) { 57 profileName, exist := session.Get().ProfileName() 58 if !exist { 59 // Check for a default if no profiles are selected 60 profileName, _, _ = loginLib.GetProfiles() 61 if len(profileName) == 0 { 62 i18n.Help().HaveYouLoggedIn() 63 return config.Profile{}, nil, singletonsI18n.ProfileDoesNotExist() 64 } 65 } 66 67 profile, err := config.Profiles().Get(profileName) 68 if err != nil { 69 return config.Profile{}, nil, err 70 } 71 72 selectedNetwork, _ := env.GetSelectedNetwork() 73 if selectedNetwork == "" { 74 i18n.Help().HaveYouSelectedANetwork() 75 return config.Profile{}, nil, singletonsI18n.NoNetworkSelected() 76 } 77 78 url, err := getClientUrl() 79 if err != nil { 80 return config.Profile{}, nil, err 81 } 82 83 ops := []http.Option{http.URL(url), http.Auth(profile.Token)} 84 client, err := client.New(states.Context, ops...) 85 if err != nil { 86 return profile, nil, singletonsI18n.CreatingAuthClientFailed(err) 87 } 88 89 return profile, client, nil 90 }