Unverified Commit 70424038 authored by Kevin Lyda's avatar Kevin Lyda
Browse files

Add SSH FETCH

parent 79dd1831
Loading
Loading
Loading
Loading
+40 −1
Original line number Diff line number Diff line
package repl

import (
	"bufio"
	"bytes"
	"fmt"
	"net/http"
	"strings"

	"git.lyda.ie/kevin/bulletin/ask"
@@ -206,7 +209,7 @@ func ActionSSHAdd(cmd *dclish.Command) error {
		fmt.Printf("ERROR: Failed to read ssh key (%s).\n", err)
		return nil
	}
	key.Add(login, sshkey)
	key.Add(u.Login, sshkey)
	fmt.Println("Key is added.")
	return nil
}
@@ -276,3 +279,39 @@ func ActionSSHDelete(cmd *dclish.Command) error {
	fmt.Println("Key deleted.")
	return nil
}

// ActionSSHFetch handles the `SSH FETCH` command.
func ActionSSHFetch(cmd *dclish.Command) error {
	sites := map[string]string{
		"codeberg": "https://codeberg.org/%s.keys",
		"gitlab":   "https://gitlab.com/%s.keys",
		"github":   "https://github.com/%s.keys",
	}
	siteTemplate := sites[strings.ToLower(cmd.Args[0])]
	if siteTemplate == "" {
		fmt.Println("ERROR: site nickname unknown.")
		return nil
	}
	site := fmt.Sprintf(siteTemplate, cmd.Args[1])
	resp, err := http.Get(site)
	if err != nil {
		fmt.Printf("ERROR: Failed to fetch ssh keys (%s).\n", err)
		return nil
	}
	scanner := bufio.NewScanner(resp.Body)
	keys := 0
	for scanner.Scan() {
		keyline := string(bytes.TrimSpace(scanner.Bytes()))
		key.Add(this.User.Login, keyline)
		keys++
	}
	switch keys {
	case 0:
		fmt.Println("No keys added.")
	case 1:
		fmt.Println("Key is added.")
	default:
		fmt.Printf("%d keys added.\n", keys)
	}
	return nil
}
+22 −2
Original line number Diff line number Diff line
@@ -1079,7 +1079,7 @@ The following actions are available:

The following commands are available:
    
  ADD        DELETE     LIST
  ADD        DELETE     FETCH      LIST
`,
		Action: ActionSSH,
		Commands: dclish.Commands{
@@ -1106,6 +1106,26 @@ The following commands are available:
				Action:  ActionSSHDelete,
				MaxArgs: 1,
			},
			"FETCH": {
				Description: `  
  Fetches  ssh keys  for a user from a site like github.

  The following sites are supported:

    +---------------+--------------------------------+
    | Site Nickname | Site key url                   |
    +---------------+--------------------------------+
    | codeberg      | https://codeberg.org/USER.keys |
    | gitlab        | https://gitlab.com/USER.keys   |
    | github        | https://github.com/USER.keys   |
    +---------------+--------------------------------+

    Format:
      SSH FETCH site-nickname site-username`,
				Action:  ActionSSHFetch,
				MinArgs: 2,
				MaxArgs: 2,
			},
			"LIST": {
				Description: `  Prints a list of ssh keys for a  user. Only an admin can list ssh keys
  for another user.