auth.go

 1package main
 2
 3import (
 4	"errors"
 5	"strings"
 6
 7	"github.com/charmbracelet/soft-serve/server/auth"
 8	"github.com/charmbracelet/soft-serve/server/backend"
 9	"github.com/charmbracelet/soft-serve/server/sshutils"
10	"github.com/spf13/cobra"
11)
12
13var (
14	password  string
15	publicKey string
16)
17
18var authCmd = &cobra.Command{
19	Use:     "auth [username]",
20	Aliases: []string{"authenticate"},
21	Short:   "Authenticate user",
22	RunE: func(cmd *cobra.Command, args []string) error {
23		ctx := cmd.Context()
24		be := backend.FromContext(ctx)
25
26		// TODO: add password support
27		// if password == "" && publicKey == "" {
28		// 	return errors.New("must specify either a password or public key")
29		// }
30
31		publicKey = strings.TrimSpace(publicKey)
32		if publicKey == "" {
33			return errors.New("must specify a public key")
34		}
35
36		pk, _, err := sshutils.ParseAuthorizedKey(publicKey)
37		if err != nil {
38			return err
39		}
40
41		user, err := be.Authenticate(ctx, auth.NewPublicKey(pk))
42		if err != nil {
43			return err
44		}
45
46		out := cmd.OutOrStdout()
47		if ojson {
48			return writeJSON(out, user)
49		} else {
50			cmd.Printf("User %s authenticated successfully\n", user.Username())
51		}
52
53		return nil
54	},
55}
56
57func init() {
58	authCmd.Flags().StringVarP(&password, "password", "p", "", "password")
59	authCmd.Flags().StringVarP(&publicKey, "public-key", "k", "", "public key")
60}