aboutsummaryrefslogtreecommitdiff
path: root/examples/password_input.lua
diff options
context:
space:
mode:
Diffstat (limited to 'examples/password_input.lua')
-rw-r--r--examples/password_input.lua59
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 @@
1local sys = require "system"
2
3print [[
4
5This example shows how to disable the "echo" of characters read to the console,
6useful 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(...)`
15local 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
37end
38
39
40
41-- Get username
42io.write("Username: ")
43local username = io.stdin:read("*l")
44
45-- Get the secret
46io.write("Password: ")
47local password = read_secret("*l")
48
49-- Get domainname
50io.write("Domain : ")
51local domain = io.stdin:read("*l")
52
53
54-- Print the results
55print("")
56print("Here's what we got:")
57print(" username: " .. username)
58print(" password: " .. password)
59print(" domain : " .. domain)