github.com/Venafi/vcert/v5@v5.10.2/pkg/venafi/cloud/oauth.go (about)

     1  package cloud
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/Venafi/vcert/v5/pkg/verror"
     9  )
    10  
    11  type TLSPCAccessTokenResponse struct {
    12  	AccessToken string `json:"access_token"`
    13  	TokenType   string `json:"token_type"`
    14  	ExpiresIn   int64  `json:"expires_in"`
    15  	Scope       string `json:"scope,omitempty"`
    16  }
    17  
    18  func parseAccessTokenResponse(expectedStatusCode int, statusCode int, httpStatus string, body []byte) (*TLSPCAccessTokenResponse, error) {
    19  	if expectedStatusCode == statusCode {
    20  		return parseAccessTokenData(body)
    21  	}
    22  
    23  	errors, err := parseResponseErrors(body)
    24  	if err != nil {
    25  		// Parsing the error failed, return the original error
    26  		bodyText := strings.TrimSpace(string(body))
    27  		if bodyText == "" {
    28  			return nil, fmt.Errorf("%w: %s", verror.ServerError, httpStatus)
    29  		}
    30  		return nil, fmt.Errorf("%w: %s, %s", verror.ServerError, httpStatus, bodyText)
    31  	}
    32  	respError := fmt.Sprintf("unexpected status code on Venafi Cloud Authentication. Status: %s\n", httpStatus)
    33  	for _, e := range errors {
    34  		respError += fmt.Sprintf("Error Code: %d Error: %s\n", e.Code, e.Message)
    35  	}
    36  	return nil, fmt.Errorf("%w: %v", verror.ServerError, respError)
    37  }
    38  
    39  func parseAccessTokenData(data []byte) (*TLSPCAccessTokenResponse, error) {
    40  	var response TLSPCAccessTokenResponse
    41  	err := json.Unmarshal(data, &response)
    42  	if err != nil {
    43  		return nil, fmt.Errorf("%w: %v", verror.ServerError, err)
    44  	}
    45  
    46  	return &response, nil
    47  }