github.com/cloudfoundry-community/cloudfoundry-cli@v6.44.1-0.20240130060226-cda5ed8e89a5+incompatible/actor/v2action/auth.go (about)

     1  package v2action
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"code.cloudfoundry.org/cli/actor/actionerror"
     7  	"code.cloudfoundry.org/cli/api/uaa/constant"
     8  	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
     9  )
    10  
    11  // Authenticate authenticates the user in UAA and sets the returned tokens in
    12  // the config.
    13  //
    14  // It unsets the currently targeted org and space whether authentication
    15  // succeeds or not.
    16  func (actor Actor) Authenticate(ID string, secret string, origin string, grantType constant.GrantType) error {
    17  	if grantType == constant.GrantTypePassword && actor.Config.UAAGrantType() == string(constant.GrantTypeClientCredentials) {
    18  		return actionerror.PasswordGrantTypeLogoutRequiredError{}
    19  	}
    20  
    21  	actor.Config.UnsetOrganizationAndSpaceInformation()
    22  	credentials := make(map[string]string)
    23  
    24  	if grantType == constant.GrantTypePassword {
    25  		credentials["username"] = ID
    26  		credentials["password"] = secret
    27  	} else if grantType == constant.GrantTypeClientCredentials {
    28  		credentials["client_id"] = ID
    29  		credentials["client_secret"] = secret
    30  	}
    31  
    32  	accessToken, refreshToken, err := actor.UAAClient.Authenticate(credentials, origin, grantType)
    33  	if err != nil {
    34  		actor.Config.SetTokenInformation("", "", "")
    35  		return err
    36  	}
    37  
    38  	accessToken = fmt.Sprintf("bearer %s", accessToken)
    39  	actor.Config.SetTokenInformation(accessToken, refreshToken, "")
    40  
    41  	if grantType == constant.GrantTypePassword {
    42  		actor.Config.SetUAAGrantType("")
    43  	} else {
    44  		actor.Config.SetUAAGrantType(string(grantType))
    45  	}
    46  
    47  	if grantType == constant.GrantTypeClientCredentials {
    48  		actor.Config.SetUAAClientCredentials(ID, "")
    49  	}
    50  
    51  	return nil
    52  }
    53  
    54  func (actor Actor) GetLoginPrompts() map[string]coreconfig.AuthPrompt {
    55  	rawPrompts := actor.UAAClient.LoginPrompts()
    56  	prompts := make(map[string]coreconfig.AuthPrompt)
    57  	for key, val := range rawPrompts {
    58  		prompts[key] = coreconfig.AuthPrompt{
    59  			Type:        knownAuthPromptTypes[val[0]],
    60  			DisplayName: val[1],
    61  		}
    62  	}
    63  	return prompts
    64  }
    65  
    66  var knownAuthPromptTypes = map[string]coreconfig.AuthPromptType{
    67  	"text":     coreconfig.AuthPromptTypeText,
    68  	"password": coreconfig.AuthPromptTypePassword,
    69  }