forked from gopasspw/gopass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
promptpass_others.go
51 lines (43 loc) · 1.15 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
//go:build !windows
// +build !windows
package termio
import (
"context"
"fmt"
"os"
"os/signal"
"golang.org/x/term"
"github.com/gopasspw/gopass/internal/out"
"github.com/gopasspw/gopass/pkg/ctxutil"
)
// 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 := term.GetState(fd)
if err != nil {
return "", fmt.Errorf("could not get state of terminal: %w", err)
}
defer func() {
if err := term.Restore(fd, oldState); err != nil {
out.Errorf(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 := term.Restore(fd, oldState); err != nil {
out.Errorf(ctx, "Failed to restore terminal: %s", err)
}
os.Exit(1)
}()
fmt.Fprintf(Stdout, "%s: ", prompt)
passBytes, err := term.ReadPassword(fd)
fmt.Fprintln(Stdout, "")
return string(passBytes), err
}