summaryrefslogtreecommitdiffstats
path: root/client/go/cmd/login.go
blob: f9ea90a6e555e2b4c82a20e51686ce69cf579d9e (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
82
83
84
85
86
87
88
89
90
91
92
93
package cmd

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/pkg/browser"
	"github.com/spf13/cobra"
	"github.com/vespa-engine/vespa/client/go/auth"
	"github.com/vespa-engine/vespa/client/go/auth/auth0"
)

// newLoginCmd runs the login flow guiding the user through the process
// by showing the login instructions, opening the browser.
// Use `expired` to run the login from other commands setup:
// this will only affect the messages.
func newLoginCmd(cli *CLI) *cobra.Command {
	return &cobra.Command{
		Use:               "login",
		Args:              cobra.NoArgs,
		Short:             "Authenticate the Vespa CLI",
		Example:           "$ vespa auth login",
		DisableAutoGenTag: true,
		SilenceUsage:      true,
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := cmd.Context()
			targetType, err := cli.config.targetType()
			if err != nil {
				return err
			}
			system, err := cli.system(targetType)
			if err != nil {
				return err
			}
			a, err := auth0.New(cli.config.authConfigPath(), system.Name, system.URL)
			if err != nil {
				return err
			}
			state, err := a.Authenticator.Start(ctx)
			if err != nil {
				return fmt.Errorf("could not start the authentication process: %w", err)
			}

			log.Printf("Your Device Confirmation code is: %s\n\n", state.UserCode)

			log.Println("If you prefer, you can open the URL directly for verification")
			log.Printf("Your Verification URL: %s\n\n", state.VerificationURI)

			log.Println("Press Enter to open the browser to log in or ^C to quit...")
			fmt.Scanln()

			err = browser.OpenURL(state.VerificationURI)

			if err != nil {
				log.Printf("Couldn't open the URL, please do it manually: %s.", state.VerificationURI)
			}

			var res auth.Result
			err = cli.spinner(os.Stderr, "Waiting for login to complete in browser ...", func() error {
				res, err = a.Authenticator.Wait(ctx, state)
				return err
			})

			if err != nil {
				return fmt.Errorf("login error: %w", err)
			}

			log.Print("\n")
			log.Println("Successfully logged in.")
			log.Print("\n")

			// store the refresh token
			secretsStore := &auth.Keyring{}
			err = secretsStore.Set(auth.SecretsNamespace, system.Name, res.RefreshToken)
			if err != nil {
				// log the error but move on
				log.Println("Could not store the refresh token locally, please expect to login again once your access token expired.")
			}

			creds := auth0.Credentials{
				AccessToken: res.AccessToken,
				ExpiresAt:   time.Now().Add(time.Duration(res.ExpiresIn) * time.Second),
				Scopes:      auth.RequiredScopes(),
			}
			if err := a.WriteCredentials(creds); err != nil {
				return fmt.Errorf("failed to write credentials: %w", err)
			}
			return err
		},
	}
}