-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_login.go
More file actions
83 lines (73 loc) · 2.22 KB
/
Copy pathauth_login.go
File metadata and controls
83 lines (73 loc) · 2.22 KB
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
package cmd
import (
"errors"
"fmt"
"os"
"strings"
"github.com/loops-so/cli/internal/api"
"github.com/loops-so/cli/internal/config"
"github.com/spf13/cobra"
"golang.org/x/term"
)
var loginName string
var loginSkipVerify bool
var loginCmd = &cobra.Command{
Use: "login",
Short: "Authenticate with your Loops API key",
RunE: func(cmd *cobra.Command, args []string) error {
if loginName == "" {
return errors.New("use --name to give this key a name (e.g. loops auth login --name my-team)")
}
fmt.Fprint(os.Stderr, "Enter your API key: ")
raw, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr)
if err != nil {
return fmt.Errorf("failed to read API key: %w", err)
}
apiKey := strings.TrimSpace(string(raw))
if apiKey == "" {
return fmt.Errorf("API key cannot be empty")
}
result, err := runAuthLogin(apiKey, loginName, loginSkipVerify)
if err != nil {
return err
}
if isJSONOutput() {
msg := fmt.Sprintf("API key saved as %q", loginName)
if result != nil {
msg = fmt.Sprintf("Authenticated as team: %s", result.TeamName)
}
return printJSON(cmd.OutOrStdout(), Result{Success: true, Message: msg})
}
if result != nil {
fmt.Fprintf(cmd.OutOrStdout(), "API key saved as %q. Authenticated as team: %s\n", loginName, result.TeamName)
} else {
fmt.Fprintf(cmd.OutOrStdout(), "API key saved as %q.\n", loginName)
}
return nil
},
}
func runAuthLogin(apiKey, name string, skipVerify bool) (*api.APIKeyResponse, error) {
if name == "" {
return nil, errors.New("use --name to give this key a name")
}
if skipVerify {
if err := config.Save(apiKey, name); err != nil {
return nil, err
}
return nil, nil
}
result, err := newAPIClient(&config.Config{EndpointURL: config.EndpointURL(), APIKey: apiKey, Debug: debugFlag}).GetAPIKey()
if err != nil {
return nil, fmt.Errorf("API key verification failed: %w", err)
}
if err := config.Save(apiKey, name); err != nil {
return nil, err
}
return result, nil
}
func init() {
loginCmd.Flags().StringVarP(&loginName, "name", "n", "", "Name for this API key (e.g. my-team)")
loginCmd.Flags().BoolVar(&loginSkipVerify, "skip-verify", false, "Save the API key without verifying it")
authCmd.AddCommand(loginCmd)
}