identity.go raw

   1  package internal
   2  
   3  import (
   4  	"context"
   5  	"encoding/json"
   6  	"io"
   7  	"net/http"
   8  	"time"
   9  
  10  	"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
  11  )
  12  
  13  // DefaultIdentityURL represents the Identity API endpoint to call.
  14  const DefaultIdentityURL = "https://identity.api.rackspacecloud.com/v2.0/tokens"
  15  
  16  type Identifier struct {
  17  	baseURL    string
  18  	httpClient *http.Client
  19  }
  20  
  21  // NewIdentifier creates a new Identifier.
  22  func NewIdentifier(httpClient *http.Client, baseURL string) *Identifier {
  23  	if httpClient == nil {
  24  		httpClient = &http.Client{Timeout: 5 * time.Second}
  25  	}
  26  
  27  	if baseURL == "" {
  28  		baseURL = DefaultIdentityURL
  29  	}
  30  
  31  	return &Identifier{baseURL: baseURL, httpClient: httpClient}
  32  }
  33  
  34  // Login sends an authentication request.
  35  // https://docs.rackspace.com/docs/cloud-dns/v1/getting-started/authenticate
  36  func (a *Identifier) Login(ctx context.Context, apiUser, apiKey string) (*Identity, error) {
  37  	authData := AuthData{
  38  		Auth: Auth{
  39  			APIKeyCredentials: APIKeyCredentials{
  40  				Username: apiUser,
  41  				APIKey:   apiKey,
  42  			},
  43  		},
  44  	}
  45  
  46  	req, err := newJSONRequest(ctx, http.MethodPost, a.baseURL, authData)
  47  	if err != nil {
  48  		return nil, err
  49  	}
  50  
  51  	resp, err := a.httpClient.Do(req)
  52  	if err != nil {
  53  		return nil, errutils.NewHTTPDoError(req, err)
  54  	}
  55  
  56  	defer func() { _ = resp.Body.Close() }()
  57  
  58  	if resp.StatusCode != http.StatusOK {
  59  		return nil, errutils.NewUnexpectedResponseStatusCodeError(req, resp)
  60  	}
  61  
  62  	raw, err := io.ReadAll(resp.Body)
  63  	if err != nil {
  64  		return nil, errutils.NewReadResponseError(req, resp.StatusCode, err)
  65  	}
  66  
  67  	var identity Identity
  68  
  69  	err = json.Unmarshal(raw, &identity)
  70  	if err != nil {
  71  		return nil, errutils.NewUnmarshalError(req, resp.StatusCode, raw, err)
  72  	}
  73  
  74  	return &identity, nil
  75  }
  76