-
Notifications
You must be signed in to change notification settings - Fork 1
/
login.go
85 lines (69 loc) · 1.84 KB
/
login.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
package account
import (
"context"
"errors"
"fmt"
"log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/netsoc/cli/pkg/config"
"github.com/netsoc/cli/pkg/util"
iam "github.com/netsoc/iam/client"
)
type loginOptions struct {
Config func() (*config.Config, error)
IAMClient func() (*iam.APIClient, error)
Force bool
Username string
}
// NewCmdLogin creates a new account login command
func NewCmdLogin(f *util.CmdFactory) *cobra.Command {
opts := loginOptions{
Config: f.Config,
IAMClient: f.IAMClient,
}
cmd := &cobra.Command{
Use: "login <username>",
Short: "Log in to account",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Username = args[0]
return loginRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "log in even if already logged in")
return cmd
}
func loginRun(opts loginOptions) error {
c, err := opts.Config()
if err != nil {
return err
}
client, err := opts.IAMClient()
if err != nil {
return err
}
if c.Token != "" && !opts.Force {
ctx := context.WithValue(context.Background(), iam.ContextAccessToken, c.Token)
u, _, err := client.UsersApi.GetUser(ctx, "self")
if err != nil {
log.Printf("failed to get info about user: %v", util.APIError(err))
return errors.New("already logged in")
}
return fmt.Errorf(fmt.Sprintf("already logged in as %v", u.Username))
}
p, err := util.ReadPassword(false)
if err != nil {
return fmt.Errorf("failed to get password: %w", err)
}
t, _, err := client.UsersApi.Login(context.Background(), opts.Username, iam.LoginRequest{Password: p})
if err != nil {
return util.APIError(err)
}
viper.Set("token", t.Token)
if err := viper.WriteConfig(); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
log.Println("Logged in successfully")
return nil
}