github.com/instill-ai/component@v0.16.0-beta/pkg/connector/restapi/v0/auth.go (about)

     1  package restapi
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/instill-ai/component/pkg/connector/util/httpclient"
     7  	"github.com/instill-ai/x/errmsg"
     8  )
     9  
    10  type authType string
    11  
    12  const (
    13  	noAuthType      authType = "NO_AUTH"
    14  	basicAuthType   authType = "BASIC_AUTH"
    15  	apiKeyType      authType = "API_KEY"
    16  	bearerTokenType authType = "BEARER_TOKEN"
    17  )
    18  
    19  type authentication interface {
    20  	setAuthInClient(c *httpclient.Client) error
    21  }
    22  
    23  type noAuth struct {
    24  	AuthType authType `json:"auth_type"`
    25  }
    26  
    27  func (a noAuth) setAuthInClient(_ *httpclient.Client) error {
    28  	return nil
    29  }
    30  
    31  type basicAuth struct {
    32  	AuthType authType `json:"auth_type"`
    33  	Username string   `json:"username"`
    34  	Password string   `json:"password"`
    35  }
    36  
    37  func (a basicAuth) setAuthInClient(c *httpclient.Client) error {
    38  	if a.Username == "" || a.Password == "" {
    39  		return errmsg.AddMessage(
    40  			fmt.Errorf("invalid auth"),
    41  			"Basic Auth error: username or password is empty.",
    42  		)
    43  	}
    44  
    45  	c.SetBasicAuth(a.Username, a.Password)
    46  
    47  	return nil
    48  }
    49  
    50  type authLocation string
    51  
    52  const (
    53  	header authLocation = "header"
    54  	query  authLocation = "query"
    55  )
    56  
    57  type apiKeyAuth struct {
    58  	AuthType     authType     `json:"auth_type"`
    59  	Key          string       `json:"key"`
    60  	Value        string       `json:"value"`
    61  	AuthLocation authLocation `json:"auth_location"`
    62  }
    63  
    64  func (a apiKeyAuth) setAuthInClient(c *httpclient.Client) error {
    65  	if a.Key == "" || a.Value == "" {
    66  		return errmsg.AddMessage(
    67  			fmt.Errorf("invalid auth"),
    68  			"API Key Auth error: key or value is empty.",
    69  		)
    70  	}
    71  
    72  	if a.AuthLocation == header {
    73  		c.SetHeader(a.Key, a.Value)
    74  		return nil
    75  	}
    76  
    77  	c.SetQueryParam(a.Key, a.Value)
    78  
    79  	return nil
    80  }
    81  
    82  type bearerTokenAuth struct {
    83  	AuthType authType `json:"auth_type"`
    84  	Token    string   `json:"token"`
    85  }
    86  
    87  func (a bearerTokenAuth) setAuthInClient(c *httpclient.Client) error {
    88  	if a.Token == "" {
    89  		return errmsg.AddMessage(
    90  			fmt.Errorf("invalid auth"),
    91  			"Bearer Token Auth error: token is empty.",
    92  		)
    93  	}
    94  
    95  	c.SetAuthToken(a.Token)
    96  
    97  	return nil
    98  }