-
Notifications
You must be signed in to change notification settings - Fork 2
/
read_password.go
128 lines (110 loc) · 2.22 KB
/
read_password.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package adm
import (
"errors"
"fmt"
"os"
"github.com/peterh/liner"
)
const (
promptPassword = `Enter password: `
repeatPassword = `Repeat password: `
promptToken = `Enter token: `
repeatToken = `Repeat token: `
promptUser = `Username: `
SUCCESS = "\xe2\x9c\x94"
FAILURE = "\xe2\x9c\x98"
RED = "\x1b[31m"
GREEN = "\x1b[32m"
CLEAR = "\x1b[0m"
)
var ErrPMismatch = errors.New(`Passwords did not match`)
var ErrTMismatch = errors.New(`Tokens did not match`)
func Read(style string) (string, error) {
var (
pass string
err error
)
line := liner.NewLiner()
defer line.Close()
line.SetCtrlCAborts(true)
switch style {
case `password`:
pass, err = line.PasswordPrompt(promptPassword)
case `token`:
pass, err = line.PasswordPrompt(promptToken)
case `user`:
pass, err = line.Prompt(promptUser)
}
if err != nil {
return "", err
}
return pass, nil
}
func ReadConfirmed(style string) (string, error) {
var (
pass, again string
err error
)
line := liner.NewLiner()
defer line.Close()
line.SetCtrlCAborts(true)
// first pass
switch style {
case `password`:
pass, err = line.PasswordPrompt(promptPassword)
case `token`:
pass, err = line.PasswordPrompt(promptToken)
}
if err != nil {
return "", err
}
// second pass
switch style {
case `password`:
again, err = line.PasswordPrompt(repeatPassword)
case `token`:
again, err = line.PasswordPrompt(repeatToken)
}
if err != nil {
return "", err
}
// compare passwords
if pass != again {
switch style {
case `password`:
return "", ErrPMismatch
case `token`:
return "", ErrTMismatch
}
}
return pass, nil
}
func ReadVerified(style string) string {
var (
password string
err error
)
read_loop:
for password == "" {
if password, err = ReadConfirmed(style); err == liner.ErrPromptAborted {
os.Exit(0)
} else if err == ErrPMismatch || err == ErrTMismatch {
fmt.Fprintf(
os.Stderr,
RED+FAILURE+CLEAR+" %s\n",
err.Error(),
)
continue read_loop
} else if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
fmt.Fprintf(
os.Stderr,
GREEN+SUCCESS+CLEAR+" %s%s%s\n",
`Entered `, style, `s match`,
)
return password
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix