identity.go raw

   1  package internal
   2  
   3  import (
   4  	"context"
   5  	"errors"
   6  	"fmt"
   7  	"net/http"
   8  
   9  	"golang.org/x/oauth2"
  10  )
  11  
  12  // OauthConfiguration credentials.
  13  type OauthConfiguration struct {
  14  	OAuth2ClientID string
  15  	OAuth2SecretID string
  16  	Username       string
  17  	Password       string
  18  }
  19  
  20  func (config *OauthConfiguration) Validate() error {
  21  	msg := " is missing in credentials information"
  22  
  23  	if config.Username == "" {
  24  		return errors.New("username" + msg)
  25  	}
  26  
  27  	if config.Password == "" {
  28  		return errors.New("password" + msg)
  29  	}
  30  
  31  	if config.OAuth2ClientID == "" {
  32  		return errors.New("serviceID" + msg)
  33  	}
  34  
  35  	if config.OAuth2SecretID == "" {
  36  		return errors.New("secret" + msg)
  37  	}
  38  
  39  	return nil
  40  }
  41  
  42  func NewOauthClient(ctx context.Context, config *OauthConfiguration) (*http.Client, error) {
  43  	err := config.Validate()
  44  	if err != nil {
  45  		return nil, err
  46  	}
  47  
  48  	oauth2Config := oauth2.Config{
  49  		ClientID:     config.OAuth2ClientID,
  50  		ClientSecret: config.OAuth2SecretID,
  51  		Endpoint: oauth2.Endpoint{
  52  			TokenURL:  tokenURL,
  53  			AuthStyle: oauth2.AuthStyleInParams,
  54  		},
  55  		Scopes: []string{".+:/dns-master/.+"},
  56  	}
  57  
  58  	oauth2Token, err := oauth2Config.PasswordCredentialsToken(ctx, config.Username, config.Password)
  59  	if err != nil {
  60  		return nil, fmt.Errorf("failed to create oauth2 token: %w", err)
  61  	}
  62  
  63  	return oauth2Config.Client(ctx, oauth2Token), nil
  64  }
  65