github.com/wanddynosios/cli/v8@v8.7.9-0.20240221182337-1a92e3a7017f/command/v7/auth_command.go (about)

     1  package v7
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"code.cloudfoundry.org/cli/api/uaa/constant"
     7  	"code.cloudfoundry.org/cli/api/uaa/uaaversion"
     8  	"code.cloudfoundry.org/cli/command"
     9  	"code.cloudfoundry.org/cli/command/flag"
    10  	"code.cloudfoundry.org/cli/command/translatableerror"
    11  	"code.cloudfoundry.org/cli/command/v7/shared"
    12  )
    13  
    14  type AuthCommand struct {
    15  	BaseCommand
    16  
    17  	RequiredArgs      flag.Authentication `positional-args:"yes"`
    18  	ClientCredentials bool                `long:"client-credentials" description:"Use (non-user) service account (also called client credentials)"`
    19  	Origin            string              `long:"origin" description:"Indicates the identity provider to be used for authentication"`
    20  	usage             interface{}         `usage:"CF_NAME auth USERNAME PASSWORD\n   CF_NAME auth USERNAME PASSWORD --origin ORIGIN\n   CF_NAME auth CLIENT_ID CLIENT_SECRET --client-credentials\n\nENVIRONMENT VARIABLES:\n   CF_USERNAME=user          Authenticating user. Overridden if USERNAME argument is provided.\n   CF_PASSWORD=password      Password associated with user. Overridden if PASSWORD argument is provided.\n\nWARNING:\n   Providing your password as a command line option is highly discouraged\n   Your password may be visible to others and may be recorded in your shell history\n   Consider using the CF_PASSWORD environment variable instead\n\nEXAMPLES:\n   CF_NAME auth name@example.com \"my password\" (use quotes for passwords with a space)\n   CF_NAME auth name@example.com \"\\\"password\\\"\" (escape quotes if used in password)"`
    21  	relatedCommands   interface{}         `related_commands:"api, login, target"`
    22  }
    23  
    24  func (cmd AuthCommand) Execute(args []string) error {
    25  	if len(cmd.Origin) > 0 {
    26  		uaaVersion, err := cmd.Actor.GetUAAAPIVersion()
    27  		if err != nil {
    28  			return err
    29  		}
    30  
    31  		err = command.MinimumUAAAPIVersionCheck(uaaVersion, uaaversion.MinUAAClientVersion, "Option '--origin'")
    32  		if err != nil {
    33  			return err
    34  		}
    35  	}
    36  
    37  	if cmd.ClientCredentials && cmd.Origin != "" {
    38  		return translatableerror.ArgumentCombinationError{
    39  			Args: []string{"--client-credentials", "--origin"},
    40  		}
    41  	}
    42  
    43  	username, password, err := cmd.getUsernamePassword()
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	cmd.UI.DisplayTextWithFlavor(
    49  		"API endpoint: {{.Endpoint}}",
    50  		map[string]interface{}{
    51  			"Endpoint": cmd.Config.Target(),
    52  		})
    53  
    54  	versionWarning, err := shared.CheckCCAPIVersion(cmd.Config.APIVersion())
    55  	if err != nil {
    56  		cmd.UI.DisplayWarning("Warning: unable to determine whether targeted API's version meets minimum supported.")
    57  	}
    58  	if versionWarning != "" {
    59  		cmd.UI.DisplayWarning(versionWarning)
    60  	}
    61  
    62  	if !cmd.ClientCredentials {
    63  		if cmd.Config.UAAGrantType() == string(constant.GrantTypeClientCredentials) {
    64  			return translatableerror.PasswordGrantTypeLogoutRequiredError{}
    65  		} else if cmd.Config.UAAOAuthClient() != "cf" || cmd.Config.UAAOAuthClientSecret() != "" {
    66  			return translatableerror.ManualClientCredentialsError{}
    67  		}
    68  	}
    69  
    70  	cmd.UI.DisplayNewline()
    71  
    72  	cmd.UI.DisplayText("Authenticating...")
    73  
    74  	credentials := make(map[string]string)
    75  	grantType := constant.GrantTypePassword
    76  	if cmd.ClientCredentials {
    77  		grantType = constant.GrantTypeClientCredentials
    78  		credentials["client_id"] = username
    79  		credentials["client_secret"] = password
    80  	} else {
    81  		credentials = map[string]string{
    82  			"username": username,
    83  			"password": password,
    84  		}
    85  	}
    86  
    87  	err = cmd.Actor.Authenticate(credentials, cmd.Origin, grantType)
    88  	if err != nil {
    89  		return err
    90  	}
    91  
    92  	cmd.UI.DisplayOK()
    93  	cmd.UI.DisplayTextWithFlavor(
    94  		"Use '{{.Command}}' to view or set your target org and space.",
    95  		map[string]interface{}{
    96  			"Command": fmt.Sprintf("%s target", cmd.Config.BinaryName()),
    97  		})
    98  
    99  	return nil
   100  }
   101  
   102  func (cmd AuthCommand) getUsernamePassword() (string, string, error) {
   103  	var (
   104  		userMissing     bool
   105  		passwordMissing bool
   106  	)
   107  
   108  	username := cmd.RequiredArgs.Username
   109  	if username == "" {
   110  		if envUser := cmd.Config.CFUsername(); envUser != "" {
   111  			username = envUser
   112  		} else {
   113  			userMissing = true
   114  		}
   115  	}
   116  
   117  	password := cmd.RequiredArgs.Password
   118  	if password == "" {
   119  		if envPassword := cmd.Config.CFPassword(); envPassword != "" {
   120  			password = envPassword
   121  		} else {
   122  			passwordMissing = true
   123  		}
   124  	}
   125  
   126  	if cmd.Config.IsCFOnK8s() {
   127  		if !passwordMissing {
   128  			cmd.UI.DisplayWarning("Warning: password is ignored when authenticating against Kubernetes.")
   129  		}
   130  		passwordMissing = false
   131  	}
   132  
   133  	if userMissing || passwordMissing {
   134  		return "", "", translatableerror.MissingCredentialsError{
   135  			MissingUsername: userMissing,
   136  			MissingPassword: passwordMissing,
   137  		}
   138  	}
   139  
   140  	return username, password, nil
   141  }