github.com/jcarley/cli@v0.0.0-20180201210820-966d90434c30/commands/keys/add.go (about) 1 package keys 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "path/filepath" 8 "strings" 9 10 "golang.org/x/crypto/ssh" 11 12 "github.com/Sirupsen/logrus" 13 "github.com/daticahealth/cli/commands/deploykeys" 14 "github.com/daticahealth/cli/config" 15 "github.com/daticahealth/cli/models" 16 "github.com/mitchellh/go-homedir" 17 ) 18 19 func CmdAdd(name, path string, ik IKeys, id deploykeys.IDeployKeys) error { 20 if strings.ContainsAny(name, config.InvalidChars) { 21 return fmt.Errorf("Invalid key name. Names must not contain the following characters: %s", config.InvalidChars) 22 } 23 homePath, err := homedir.Expand(path) 24 if err != nil { 25 return err 26 } 27 fullPath, err := filepath.Abs(homePath) 28 if err != nil { 29 return err 30 } 31 keyBytes, err := ioutil.ReadFile(fullPath) 32 if err != nil { 33 return err 34 } 35 k, err := id.ParsePublicKey(keyBytes) 36 if err != nil { 37 return err 38 } 39 key := ssh.MarshalAuthorizedKey(k) 40 if err != nil { 41 return err 42 } 43 err = ik.Add(name, string(key)) 44 if err != nil { 45 return err 46 } 47 logrus.Printf("Key '%s' added to your account.", name) 48 logrus.Println("If you use an ssh-agent, make sure you add this key to your ssh-agent in order to push code") 49 return nil 50 } 51 52 // Add adds a new public key to the authenticated user's account 53 func (k *SKeys) Add(name, publicKey string) error { 54 body, err := json.Marshal(models.UserKey{ 55 Key: publicKey, 56 Name: name, 57 }) 58 if err != nil { 59 return err 60 } 61 headers := k.Settings.HTTPManager.GetHeaders(k.Settings.SessionToken, k.Settings.Version, k.Settings.Pod, k.Settings.UsersID) 62 resp, status, err := k.Settings.HTTPManager.Post(body, fmt.Sprintf("%s%s/keys", k.Settings.AuthHost, k.Settings.AuthHostVersion), headers) 63 if err != nil { 64 return err 65 } 66 return k.Settings.HTTPManager.ConvertResp(resp, status, nil) 67 }