Move Username() from api.go to tsh.go

This commit is contained in:
Grzegorz Zdunek
2025-11-19 14:02:23 +01:00
parent ed38babf5e
commit f7ff0ff6d1
3 changed files with 24 additions and 26 deletions
-22
View File
@@ -32,9 +32,7 @@ import (
"net"
"net/url"
"os"
"os/user"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
@@ -4972,26 +4970,6 @@ func loopbackPool(proxyAddr string) *x509.CertPool {
return certPool
}
// Username returns the current user's username
func Username() (string, error) {
u, err := user.Current()
if err != nil {
return "", trace.Wrap(err)
}
username := u.Username
// If on Windows, strip the domain name.
if runtime.GOOS == constants.WindowsOS {
idx := strings.LastIndex(username, "\\")
if idx > -1 {
username = username[idx+1:]
}
}
return username, nil
}
// AskOTP prompts the user to enter the OTP token.
func (tc *TeleportClient) AskOTP(ctx context.Context) (token string, err error) {
ctx, span := tc.Tracer.Start(
+22 -2
View File
@@ -4845,7 +4845,7 @@ func loadClientConfigFromCLIConf(cf *CLIConf, proxy string) (*client.Config, err
c.Username = cf.Username
}
if c.Username == "" {
username, err := client.Username()
username, err := Username()
if err != nil {
return nil, trace.Wrap(err)
}
@@ -4898,7 +4898,7 @@ func loadClientConfigFromCLIConf(cf *CLIConf, proxy string) (*client.Config, err
if hostLogin != "" {
c.HostLogin = hostLogin
} else {
username, err := client.Username()
username, err := Username()
if err != nil {
return nil, trace.Wrap(err)
}
@@ -6320,3 +6320,23 @@ func stringFlagToStrings(value string) []string {
}
return apiutils.Deduplicate(values)
}
// Username returns the current user's username
func Username() (string, error) {
u, err := user.Current()
if err != nil {
return "", trace.Wrap(err)
}
username := u.Username
// If on Windows, strip the domain name.
if runtime.GOOS == constants.WindowsOS {
idx := strings.LastIndex(username, "\\")
if idx > -1 {
username = username[idx+1:]
}
}
return username, nil
}
+2 -2
View File
@@ -980,7 +980,7 @@ func TestMakeClient(t *testing.T) {
require.Equal(t, "proxy:3023", tc.Config.SSHProxyAddr)
require.Equal(t, "proxy:3080", tc.Config.WebProxyAddr)
localUser, err := client.Username()
localUser, err := Username()
require.NoError(t, err)
require.Equal(t, localUser, tc.Config.Username)
@@ -3013,7 +3013,7 @@ func TestSSHHeadlessCLIFlags(t *testing.T) {
assertErr: require.NoError,
assertConfig: func(t require.TestingT, c *client.Config) {
require.Equal(t, "other-proxy:3080", c.WebProxyAddr)
currentUsername, err := client.Username()
currentUsername, err := Username()
require.NoError(t, err)
// A default username is used, not the one from envMap.
require.Equal(t, currentUsername, c.Username)