-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser_input.go
125 lines (102 loc) · 2.52 KB
/
user_input.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
// pago - a command-line password manager.
//
// License: MIT.
// See the file LICENSE.
package main
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
"syscall"
"github.com/ktr0731/go-fuzzyfinder"
"golang.org/x/term"
)
// Pick an entry using a fuzzy finder.
func pickEntry(store string, query string) (string, error) {
// Create a list of all passwords.
list, err := listFiles(store, entryFilter(store, nil))
if err != nil {
return "", fmt.Errorf("failed to list passwords: %v", err)
}
if len(list) == 0 {
return "", fmt.Errorf("no password entries found")
}
// Show an interactive fuzzy finder.
idx, err := fuzzyfinder.Find(
list,
func(i int) string {
return list[i]
},
fuzzyfinder.WithQuery(query),
)
if err != nil {
if errors.Is(err, fuzzyfinder.ErrAbort) {
return "", nil
}
return "", fmt.Errorf("fuzzy finder failed: %v", err)
}
return list[idx], nil
}
// Read a password without echo if standard input is a terminal.
func secureRead(prompt string) (string, error) {
fmt.Fprint(os.Stderr, prompt)
if term.IsTerminal(int(syscall.Stdin)) {
password, err := term.ReadPassword(int(syscall.Stdin))
fmt.Fprintln(os.Stderr)
if err != nil {
return "", err
}
return string(password), nil
}
scanner := bufio.NewScanner(os.Stdin)
if !scanner.Scan() {
return "", scanner.Err()
}
return scanner.Text(), nil
}
func askYesNo(prompt string) (bool, error) {
fmt.Fprintf(os.Stderr, "%s [y/n]: ", prompt)
// Save the terminal state to restore later.
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
return false, fmt.Errorf("failed to make terminal raw: %v", err)
}
defer func() {
_ = term.Restore(int(os.Stdin.Fd()), oldState)
}()
answer := ""
for answer != "n" && answer != "y" {
// Read a single byte from the terminal.
var input [1]byte
_, err = os.Stdin.Read(input[:])
if err != nil {
return false, fmt.Errorf("failed to read input: %v", err)
}
answer = strings.ToLower(string(input[0]))
}
_ = term.Restore(int(os.Stdin.Fd()), oldState)
fmt.Fprintln(os.Stderr)
return answer == "y", nil
}
// Ask the user to input a password, twice if confirm is true.
func readNewPassword(confirm bool) (string, error) {
pass, err := secureRead("Enter password: ")
if err != nil {
return "", err
}
if pass == "" {
return "", fmt.Errorf("empty password")
}
if confirm {
pass2, err := secureRead("Enter password (again): ")
if err != nil {
return "", err
}
if pass != pass2 {
return "", fmt.Errorf("passwords do not match")
}
}
return pass, nil
}