My method is a bit more complicated, but I feel that the end result is worth it. This requires a table of usernames and passwords to be stored in a file called "passwords.txt". They must be in table form, which is the following:
{["index"]="value", ["username"]="password", ["etc"]="etc"}
The advantage to this is that you can enter as many users as you want and read it easily.
Here is an example password file:
{["admin"]="password",["guest"]="default"}
And here is the main program.
local users = {}
local function onStart()
if not fs.exists("passwords.txt") then
print("passwords.txt required to run!")
return false
end
local f = fs.open("passwords.txt", "r")
users = textutils.unserialize(f.readAll()) --Get the entire file contents and unserialize the table
--[[
To go further in depth about unserialize, all that the function does is take
the string form of a table and convert it into an actual table]]
f.close() --Remember to close the file
if not users then
print("Something is weird in the passwords.txt file: It must be a string form of a table!")
return false
end
return true
end
local function login()
while true do
term.clear() term.setCursorPos(1,1)
term.write("Username: ")
local username = read()
term.setCursorPos(1,2)
term.write("Password: ")
local password = read("*")
term.clear() term.setCursorPos(1,1)
if not users[username] or users[username] ~= password then --Check the username and password
print("Invalid username or password.")
os.pullEvent() --Wait for the user to do something
else
print("Success!")
return true
end
end
end
local function doStuffAfterLogin()
print("Hi this does stuff")
end
if not onStart() then return false end--If the startup function does not manage to load everything required of it then stop the program
login()
doStuffAfterLogin() --They've managed to log in with valid credentials. Now continue with the rest of the program.