Skip to content

Commit

Permalink
Refactored client authentication logic
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielHougaard committed Jan 11, 2024
1 parent b72b10c commit 584f1fc
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,32 +43,36 @@ func NewClient(cnf Config) (*Client, error) {
cnf.HttpClient.SetBaseURL(cnf.HostURL)
}

if cnf.ServiceToken == "" && cnf.ClientId == "" && cnf.ClientSecret == "" {
// Add more auth strategies here later
var usingServiceToken = cnf.ServiceToken != ""
var usingUniversalAuth = cnf.ClientId != "" && cnf.ClientSecret != ""

// Check if the user got multiple configured authentication methods, or none set at all.
if usingServiceToken && usingUniversalAuth {
return nil, fmt.Errorf("you have configured multiple authentication methods, please only use one")
} else if !usingServiceToken && !usingUniversalAuth {
return nil, fmt.Errorf("you must configure a authentication method such as service tokens or Universal Auth before making calls")
}

var authToken string

if cnf.ClientId != "" && cnf.ClientSecret != "" {
if usingUniversalAuth {
token, err := Client{cnf}.UniversalMachineIdentityAuth()

if err != nil {
return nil, fmt.Errorf("unable to authenticate with universal machine identity [err=%s]", err)
}

authToken = token
cnf.HttpClient.SetAuthToken(token)
cnf.AuthStrategy = AuthStrategy.UNIVERSAL_MACHINE_IDENTITY
}
if cnf.ServiceToken != "" && authToken == "" {
authToken = cnf.ServiceToken
} else if usingServiceToken {
cnf.HttpClient.SetAuthToken(cnf.ServiceToken)
cnf.AuthStrategy = AuthStrategy.SERVICE_TOKEN
}

if authToken != "" {
cnf.HttpClient.SetAuthToken(authToken)
} else {
return nil, fmt.Errorf("no authentication credentials provided. You must define the service_token, or client_id and client_secret field of the provider")
// If no auth strategy is set, then we should return an error
return nil, fmt.Errorf("you must configure a authentication method such as service tokens or Universal Auth before making calls")
}

// These two if statements were a part of an older migration.
// And when people upgraded to the newer version, we needed a way to indicate that the EnvSlug and SecretsPath are no longer defined on a provider-level.
if cnf.EnvSlug != "" {
return nil, fmt.Errorf("you must set the environment before making calls")
}
Expand Down

0 comments on commit 584f1fc

Please sign in to comment.