diff options
Diffstat (limited to 'examples/password_input.lua')
-rw-r--r-- | examples/password_input.lua | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/examples/password_input.lua b/examples/password_input.lua new file mode 100644 index 0000000..2994062 --- /dev/null +++ b/examples/password_input.lua | |||
@@ -0,0 +1,59 @@ | |||
1 | local sys = require "system" | ||
2 | |||
3 | print [[ | ||
4 | |||
5 | This example shows how to disable the "echo" of characters read to the console, | ||
6 | useful for reading secrets from the user. | ||
7 | |||
8 | ]] | ||
9 | |||
10 | --- Function to read from stdin without echoing the input (for secrets etc). | ||
11 | -- It will (in a platform agnostic way) disable echo on the terminal, read the | ||
12 | -- input, and then re-enable echo. | ||
13 | -- @param ... Arguments to pass to `io.stdin:read()` | ||
14 | -- @return the results of `io.stdin:read(...)` | ||
15 | local function read_secret(...) | ||
16 | local w_oldflags, p_oldflags | ||
17 | |||
18 | if sys.isatty(io.stdin) then | ||
19 | -- backup settings, configure echo flags | ||
20 | w_oldflags = sys.getconsoleflags(io.stdin) | ||
21 | p_oldflags = sys.tcgetattr(io.stdin) | ||
22 | -- set echo off to not show password on screen | ||
23 | assert(sys.setconsoleflags(io.stdin, w_oldflags - sys.CIF_ECHO_INPUT)) | ||
24 | assert(sys.tcsetattr(io.stdin, sys.TCSANOW, { lflag = p_oldflags.lflag - sys.L_ECHO })) | ||
25 | end | ||
26 | |||
27 | local secret, err = io.stdin:read(...) | ||
28 | |||
29 | -- restore settings | ||
30 | if sys.isatty(io.stdin) then | ||
31 | io.stdout:write("\n") -- Add newline after reading the password | ||
32 | sys.setconsoleflags(io.stdin, w_oldflags) | ||
33 | sys.tcsetattr(io.stdin, sys.TCSANOW, p_oldflags) | ||
34 | end | ||
35 | |||
36 | return secret, err | ||
37 | end | ||
38 | |||
39 | |||
40 | |||
41 | -- Get username | ||
42 | io.write("Username: ") | ||
43 | local username = io.stdin:read("*l") | ||
44 | |||
45 | -- Get the secret | ||
46 | io.write("Password: ") | ||
47 | local password = read_secret("*l") | ||
48 | |||
49 | -- Get domainname | ||
50 | io.write("Domain : ") | ||
51 | local domain = io.stdin:read("*l") | ||
52 | |||
53 | |||
54 | -- Print the results | ||
55 | print("") | ||
56 | print("Here's what we got:") | ||
57 | print(" username: " .. username) | ||
58 | print(" password: " .. password) | ||
59 | print(" domain : " .. domain) | ||