aboutsummaryrefslogtreecommitdiffstats
path: root/commands/bridge_auth_addtoken.go
blob: 018015e4d7e2a6a9267a93c1b8adb84bc06d0d0f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package commands

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/mattn/go-isatty"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"

	"github.com/MichaelMure/git-bug/bridge"
	"github.com/MichaelMure/git-bug/bridge/core"
	"github.com/MichaelMure/git-bug/bridge/core/auth"
	"github.com/MichaelMure/git-bug/identity"
)

var (
	bridgeAuthAddTokenTarget string
)

func runBridgeTokenAdd(cmd *cobra.Command, args []string) error {
	var value string

	if bridgeAuthAddTokenTarget == "" {
		return fmt.Errorf("flag --target is required")
	}

	if !core.TargetExist(bridgeAuthAddTokenTarget) {
		return fmt.Errorf("unknown target")
	}

	if len(args) == 1 {
		value = args[0]
	} else {
		// Read from Stdin
		if isatty.IsTerminal(os.Stdin.Fd()) {
			fmt.Println("Enter the token:")
		}
		reader := bufio.NewReader(os.Stdin)
		raw, err := reader.ReadString('\n')
		if err != nil {
			return fmt.Errorf("reading from stdin: %v", err)
		}
		value = strings.TrimSuffix(raw, "\n")
	}

	user, err := identity.GetUserIdentity(repo)
	if err != nil {
		return err
	}

	token := auth.NewToken(user.Id(), value, bridgeAuthAddTokenTarget)
	if err := token.Validate(); err != nil {
		return errors.Wrap(err, "invalid token")
	}

	err = auth.Store(repo, token)
	if err != nil {
		return err
	}

	fmt.Printf("token %s added\n", token.ID())
	return nil
}

var bridgeAuthAddTokenCmd = &cobra.Command{
	Use:     "add-token [<token>]",
	Short:   "Store a new token",
	PreRunE: loadRepoEnsureUser,
	RunE:    runBridgeTokenAdd,
	Args:    cobra.MaximumNArgs(1),
}

func init() {
	bridgeAuthCmd.AddCommand(bridgeAuthAddTokenCmd)
	bridgeAuthAddTokenCmd.Flags().StringVarP(&bridgeAuthAddTokenTarget, "target", "t", "",
		fmt.Sprintf("The target of the bridge. Valid values are [%s]", strings.Join(bridge.Targets(), ",")))
	bridgeAuthAddTokenCmd.Flags().SortFlags = false
}