enbas/internal/executor/account.go

86 lines
2.3 KiB
Go
Raw Normal View History

package executor
import (
"fmt"
"codeflow.dananglin.me.uk/apollo/enbas/internal/client"
"codeflow.dananglin.me.uk/apollo/enbas/internal/config"
internalFlag "codeflow.dananglin.me.uk/apollo/enbas/internal/flag"
"codeflow.dananglin.me.uk/apollo/enbas/internal/model"
)
func getAccountID(gtsClient *client.Client, myAccount bool, accountNames internalFlag.StringSliceValue, credentialsFile string) (string, error) {
var (
accountID string
err error
)
switch {
case myAccount:
accountID, err = getMyAccountID(gtsClient, credentialsFile)
if err != nil {
return "", fmt.Errorf("unable to get your account ID: %w", err)
}
case !accountNames.Empty():
expectedNumAccountNames := 1
if !accountNames.ExpectedLength(expectedNumAccountNames) {
return "", fmt.Errorf(
"received an unexpected number of account names: want %d",
expectedNumAccountNames,
)
}
accountID, err = getTheirAccountID(gtsClient, accountNames[0])
if err != nil {
return "", fmt.Errorf("unable to get the account ID: %w", err)
}
default:
return "", NoAccountSpecifiedError{}
}
return accountID, nil
}
func getMyAccountID(gtsClient *client.Client, path string) (string, error) {
account, err := getMyAccount(gtsClient, path)
if err != nil {
return "", fmt.Errorf("received an error while getting your account details: %w", err)
}
return account.ID, nil
}
func getTheirAccountID(gtsClient *client.Client, accountURI string) (string, error) {
account, err := getAccount(gtsClient, accountURI)
if err != nil {
return "", fmt.Errorf("unable to retrieve your account: %w", err)
}
return account.ID, nil
}
func getMyAccount(gtsClient *client.Client, path string) (model.Account, error) {
authConfig, err := config.NewCredentialsConfigFromFile(path)
if err != nil {
return model.Account{}, fmt.Errorf("unable to retrieve the authentication configuration: %w", err)
}
accountURI := authConfig.CurrentAccount
account, err := getAccount(gtsClient, accountURI)
if err != nil {
return model.Account{}, fmt.Errorf("unable to retrieve your account: %w", err)
}
return account, nil
}
func getAccount(gtsClient *client.Client, accountURI string) (model.Account, error) {
account, err := gtsClient.GetAccount(accountURI)
if err != nil {
return model.Account{}, fmt.Errorf("unable to retrieve the account details: %w", err)
}
return account, nil
}