blob: 5558d82982d2d6745597392a13fe46b09b5d3316 (
plain)
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
|
// Copyright (C) MongoDB, Inc. 2014-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Package password handles cleanly reading in a user's password from
// the command line. This varies heavily between operating systems.
package password
import (
"fmt"
"github.com/mongodb/mongo-tools/legacy/log"
"os"
)
// key constants
const (
backspaceKey = 8
deleteKey = 127
eotKey = 3
eofKey = 4
newLineKey = 10
carriageReturnKey = 13
)
// Prompt displays a prompt asking for the password and returns the
// password the user enters as a string.
func Prompt() string {
var pass string
if IsTerminal() {
log.Logv(log.DebugLow, "standard input is a terminal; reading password from terminal")
fmt.Fprintf(os.Stderr, "Enter password:")
pass = GetPass()
} else {
log.Logv(log.Always, "reading password from standard input")
fmt.Fprintf(os.Stderr, "Enter password:")
pass = readPassFromStdin()
}
fmt.Fprintln(os.Stderr)
return pass
}
// readPassFromStdin pipes in a password from stdin if
// we aren't using a terminal for standard input
func readPassFromStdin() string {
pass := []byte{}
for {
var chBuf [1]byte
n, err := os.Stdin.Read(chBuf[:])
if err != nil {
panic(err)
}
if n == 0 {
break
}
ch := chBuf[0]
if ch == backspaceKey || ch == deleteKey {
if len(pass) > 0 {
pass = pass[:len(pass)-1]
}
} else if ch == carriageReturnKey || ch == newLineKey || ch == eotKey || ch == eofKey {
break
} else if ch != 0 {
pass = append(pass, ch)
}
}
return string(pass)
}
|