github.com/jcarley/cli@v0.0.0-20180201210820-966d90434c30/commands/keys/rm.go (about)

     1  package keys
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"strings"
     8  
     9  	"golang.org/x/crypto/ssh"
    10  
    11  	"github.com/Sirupsen/logrus"
    12  	"github.com/daticahealth/cli/commands/deploykeys"
    13  	"github.com/daticahealth/cli/config"
    14  )
    15  
    16  func CmdRemove(name, privateKeyPath string, ik IKeys, id deploykeys.IDeployKeys) error {
    17  	if privateKeyPath != "" {
    18  		// if ssh key auth is being used, don't let the key used for key auth be removed
    19  		b, err := ioutil.ReadFile(privateKeyPath)
    20  		if err != nil {
    21  			return err
    22  		}
    23  		privKey, err := id.ParsePrivateKey(b)
    24  		if err != nil {
    25  			return err
    26  		}
    27  		pubKey, err := id.ExtractPublicKey(privKey)
    28  		if err != nil {
    29  			return err
    30  		}
    31  		pubKeyString := string(ssh.MarshalAuthorizedKey(pubKey))
    32  		userKeys, err := ik.List()
    33  		if err != nil {
    34  			return err
    35  		}
    36  		for _, uk := range *userKeys {
    37  			if strings.TrimSpace(pubKeyString) == strings.TrimSpace(uk.Key) {
    38  				return errors.New("You cannot remove the key that is currently being used for authentication. Run \"datica clear --private-key\" to remove your SSH key authentication settings.")
    39  			}
    40  		}
    41  	}
    42  	if strings.ContainsAny(name, config.InvalidChars) {
    43  		return fmt.Errorf("Invalid key name. Names must not contain the following characters: %s", config.InvalidChars)
    44  	}
    45  	err := ik.Remove(name)
    46  	if err != nil {
    47  		return err
    48  	}
    49  	logrus.Printf("Key '%s' has been removed from your account.", name)
    50  	return nil
    51  }
    52  
    53  func (k *SKeys) Remove(name string) error {
    54  	headers := k.Settings.HTTPManager.GetHeaders(k.Settings.SessionToken, k.Settings.Version, k.Settings.Pod, k.Settings.UsersID)
    55  	resp, status, err := k.Settings.HTTPManager.Delete(nil, fmt.Sprintf("%s%s/keys/%s", k.Settings.AuthHost, k.Settings.AuthHostVersion, name), headers)
    56  	if err != nil {
    57  		return err
    58  	}
    59  	return k.Settings.HTTPManager.ConvertResp(resp, status, nil)
    60  }