-
Notifications
You must be signed in to change notification settings - Fork 38
/
auth.go
94 lines (82 loc) · 2.14 KB
/
auth.go
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
94
package cmd
import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/stateful/runme/v3/internal/auth"
"github.com/stateful/runme/v3/internal/tui"
)
func loginCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "login",
Hidden: true,
Short: "Log in to Runme (optional)",
Long: "Log in to Runme is not required for standalone functionality",
RunE: func(cmd *cobra.Command, args []string) error {
return newAuth().Login(cmd.Context())
},
}
return cmd
}
func logoutCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "logout",
Hidden: true,
Short: "Log out from Runme",
RunE: func(cmd *cobra.Command, args []string) error {
return newAuth().Logout()
},
}
return cmd
}
func tokenCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "token",
Hidden: true,
Short: "Print runme API token",
RunE: func(cmd *cobra.Command, args []string) error {
var token string
var err error
if fInsecure {
auth := newAuth()
token, err = auth.GetToken(cmd.Context())
if err != nil {
if err := checkAuthenticated(cmd.Context(), cmd, auth, !recoverableWithLogin(err)); err != nil {
return err
}
token, err = auth.GetToken(cmd.Context())
if err != nil {
return err
}
}
_, _ = fmt.Fprintln(cmd.OutOrStdout(), token)
return nil
}
return errors.New("To use this command, please add the --insecure parameter")
},
}
return cmd
}
func checkAuthenticated(ctx context.Context, cmd *cobra.Command, auth auth.Authorizer, refresh bool) error {
text := "It looks like you're not logged in. Do you want to log in now?"
if refresh {
text = "It seems that your authentication has expired. Would you like to re-authenticate now?"
}
model := tui.NewStandaloneQuestionModel(
text,
tui.MinimalKeyMap,
tui.DefaultStyles,
)
finalModel, err := newProgram(cmd, model).Run()
if err != nil {
return errors.Wrap(err, "failed to prompt")
}
shouldLogIn := finalModel.(tui.StandaloneQuestionModel).Confirmed()
if shouldLogIn {
if loginErr := auth.Login(ctx); loginErr != nil {
return errors.Wrap(loginErr, "failed to login")
}
}
return nil
}