/
login.go
84 lines (73 loc) · 1.83 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
package cli
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"github.com/micro/micro/v3/client/cli/namespace"
"github.com/micro/micro/v3/client/cli/token"
"github.com/micro/micro/v3/client/cli/util"
"github.com/micro/micro/v3/service/auth"
"github.com/urfave/cli/v2"
"golang.org/x/crypto/ssh/terminal"
)
// login flow.
// For documentation of the flow please refer to https://github.com/micro/development/pull/223
func login(ctx *cli.Context) error {
// otherwise assume username/password login
// get the environment
env, err := util.GetEnv(ctx)
if err != nil {
return err
}
// get the username
username := ctx.String("username")
// username is blank
if len(username) == 0 {
fmt.Print("Enter username: ")
// read out the username from prompt if blank
reader := bufio.NewReader(os.Stdin)
username, _ = reader.ReadString('\n')
username = strings.TrimSpace(username)
}
ns, err := namespace.Get(env.Name)
if err != nil {
return err
}
// clear tokens and try again
if err := token.Remove(ctx); err != nil {
return err
}
password := ctx.String("password")
if len(password) == 0 {
pw, err := getPassword()
if err != nil {
return err
}
password = pw
fmt.Println()
}
tok, err := auth.Token(auth.WithCredentials(username, password), auth.WithTokenIssuer(ns))
if err != nil {
return err
}
if err := token.Save(ctx, tok); err != nil {
return err
}
fmt.Println("Successfully logged in.")
return nil
}
// taken from https://stackoverflow.com/questions/2137357/getpasswd-functionality-in-go
func getPassword() (string, error) {
fmt.Print("Enter password: ")
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", err
}
password := string(bytePassword)
return strings.TrimSpace(password), nil
}
func logout(ctx *cli.Context) error {
return token.Remove(ctx)
}