forked from gopasspw/gopass
/
promptpass_others.go
52 lines (43 loc) · 1.18 KB
/
promptpass_others.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
// +build !windows
package termio
import (
"context"
"fmt"
"os"
"os/signal"
"golang.org/x/crypto/ssh/terminal"
"github.com/gopasspw/gopass/pkg/ctxutil"
"github.com/gopasspw/gopass/pkg/out"
"github.com/pkg/errors"
)
// promptPass will prompt user's for a password by terminal.
func promptPass(ctx context.Context, prompt string) (string, error) {
if !ctxutil.IsTerminal(ctx) {
return AskForString(ctx, prompt, "")
}
// Make a copy of STDIN's state to restore afterward
fd := int(os.Stdin.Fd())
oldState, err := terminal.GetState(fd)
if err != nil {
return "", errors.Errorf("Could not get state of terminal: %s", err)
}
defer func() {
if err := terminal.Restore(fd, oldState); err != nil {
out.Error(ctx, "Failed to restore terminal: %s", err)
}
}()
// Restore STDIN in the event of a signal interruption
sigch := make(chan os.Signal, 1)
signal.Notify(sigch, os.Interrupt)
go func() {
<-sigch
if err := terminal.Restore(fd, oldState); err != nil {
out.Error(ctx, "Failed to restore terminal: %s", err)
}
os.Exit(1)
}()
fmt.Fprintf(Stdout, "%s: ", prompt)
passBytes, err := terminal.ReadPassword(fd)
fmt.Fprintln(Stdout, "")
return string(passBytes), err
}