github.com/cloudfoundry/cli@v7.1.0+incompatible/cf/api/clients.go (about)

     1  package api
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"code.cloudfoundry.org/cli/cf/api/resources"
     8  	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
     9  	"code.cloudfoundry.org/cli/cf/errors"
    10  	. "code.cloudfoundry.org/cli/cf/i18n"
    11  	"code.cloudfoundry.org/cli/cf/net"
    12  )
    13  
    14  //go:generate counterfeiter . ClientRepository
    15  
    16  type ClientRepository interface {
    17  	ClientExists(clientID string) (exists bool, apiErr error)
    18  }
    19  
    20  type CloudControllerClientRepository struct {
    21  	config     coreconfig.Reader
    22  	uaaGateway net.Gateway
    23  }
    24  
    25  func NewCloudControllerClientRepository(config coreconfig.Reader, uaaGateway net.Gateway) (repo CloudControllerClientRepository) {
    26  	repo.config = config
    27  	repo.uaaGateway = uaaGateway
    28  	return
    29  }
    30  
    31  func (repo CloudControllerClientRepository) ClientExists(clientID string) (exists bool, apiErr error) {
    32  	exists = false
    33  	uaaEndpoint, apiErr := repo.getAuthEndpoint()
    34  	if apiErr != nil {
    35  		return exists, apiErr
    36  	}
    37  
    38  	path := fmt.Sprintf("%s/oauth/clients/%s", uaaEndpoint, clientID)
    39  
    40  	uaaResponse := new(resources.UAAUserResources)
    41  	apiErr = repo.uaaGateway.GetResource(path, uaaResponse)
    42  	if apiErr != nil {
    43  		if errType, ok := apiErr.(errors.HTTPError); ok {
    44  			switch errType.StatusCode() {
    45  			case http.StatusNotFound:
    46  				return false, errors.NewModelNotFoundError("Client", clientID)
    47  			case http.StatusForbidden:
    48  				return false, errors.NewAccessDeniedError()
    49  			}
    50  		}
    51  		return false, apiErr
    52  	}
    53  	return true, nil
    54  }
    55  
    56  func (repo CloudControllerClientRepository) getAuthEndpoint() (string, error) {
    57  	uaaEndpoint := repo.config.UaaEndpoint()
    58  	if uaaEndpoint == "" {
    59  		return "", errors.New(T("UAA endpoint missing from config file"))
    60  	}
    61  	return uaaEndpoint, nil
    62  }