profile_sshkeys.go raw

   1  package linodego
   2  
   3  import (
   4  	"context"
   5  	"encoding/json"
   6  	"time"
   7  
   8  	"github.com/linode/linodego/internal/parseabletime"
   9  )
  10  
  11  // SSHKey represents a SSHKey object
  12  type SSHKey struct {
  13  	ID      int        `json:"id"`
  14  	Label   string     `json:"label"`
  15  	SSHKey  string     `json:"ssh_key"`
  16  	Created *time.Time `json:"-"`
  17  }
  18  
  19  // SSHKeyCreateOptions fields are those accepted by CreateSSHKey
  20  type SSHKeyCreateOptions struct {
  21  	Label  string `json:"label"`
  22  	SSHKey string `json:"ssh_key"`
  23  }
  24  
  25  // SSHKeyUpdateOptions fields are those accepted by UpdateSSHKey
  26  type SSHKeyUpdateOptions struct {
  27  	Label string `json:"label"`
  28  }
  29  
  30  // UnmarshalJSON implements the json.Unmarshaler interface
  31  func (i *SSHKey) UnmarshalJSON(b []byte) error {
  32  	type Mask SSHKey
  33  
  34  	p := struct {
  35  		*Mask
  36  
  37  		Created *parseabletime.ParseableTime `json:"created"`
  38  	}{
  39  		Mask: (*Mask)(i),
  40  	}
  41  
  42  	if err := json.Unmarshal(b, &p); err != nil {
  43  		return err
  44  	}
  45  
  46  	i.Created = (*time.Time)(p.Created)
  47  
  48  	return nil
  49  }
  50  
  51  // GetCreateOptions converts a SSHKey to SSHKeyCreateOptions for use in CreateSSHKey
  52  func (i SSHKey) GetCreateOptions() (o SSHKeyCreateOptions) {
  53  	o.Label = i.Label
  54  	o.SSHKey = i.SSHKey
  55  
  56  	return o
  57  }
  58  
  59  // GetUpdateOptions converts a SSHKey to SSHKeyCreateOptions for use in UpdateSSHKey
  60  func (i SSHKey) GetUpdateOptions() (o SSHKeyUpdateOptions) {
  61  	o.Label = i.Label
  62  	return o
  63  }
  64  
  65  // ListSSHKeys lists SSHKeys
  66  func (c *Client) ListSSHKeys(ctx context.Context, opts *ListOptions) ([]SSHKey, error) {
  67  	return getPaginatedResults[SSHKey](ctx, c, "profile/sshkeys", opts)
  68  }
  69  
  70  // GetSSHKey gets the sshkey with the provided ID
  71  func (c *Client) GetSSHKey(ctx context.Context, keyID int) (*SSHKey, error) {
  72  	e := formatAPIPath("profile/sshkeys/%d", keyID)
  73  	return doGETRequest[SSHKey](ctx, c, e)
  74  }
  75  
  76  // CreateSSHKey creates a SSHKey
  77  func (c *Client) CreateSSHKey(ctx context.Context, opts SSHKeyCreateOptions) (*SSHKey, error) {
  78  	return doPOSTRequest[SSHKey](ctx, c, "profile/sshkeys", opts)
  79  }
  80  
  81  // UpdateSSHKey updates the SSHKey with the specified id
  82  func (c *Client) UpdateSSHKey(ctx context.Context, keyID int, opts SSHKeyUpdateOptions) (*SSHKey, error) {
  83  	e := formatAPIPath("profile/sshkeys/%d", keyID)
  84  	return doPUTRequest[SSHKey](ctx, c, e, opts)
  85  }
  86  
  87  // DeleteSSHKey deletes the SSHKey with the specified id
  88  func (c *Client) DeleteSSHKey(ctx context.Context, keyID int) error {
  89  	e := formatAPIPath("profile/sshkeys/%d", keyID)
  90  	return doDELETERequest(ctx, c, e)
  91  }
  92