· 8 years ago · Mar 25, 2018, 08:16 PM
1-- *Bank API - by Wes (eastly878)*
2-- Filename: bankAPI
3
4--
5-- Standard Utilities
6--
7-- Error Handler
8function handleError (errorMsg)
9 term.clear()
10 term.setCursorPos(1,1)
11 errorMsg = errorMsg or "Unknown error occurred"
12 print("ERROR:", errorMsg, "... rebooting.")
13 sleep(5)
14 os.reboot()
15end
16
17-- Press ENTER to continue
18function continueCheck ()
19 print("Press ENTER to continue.")
20 while true do
21 local sEvent, param = os.pullEvent("key")
22 if(sEvent == "key") then
23 if param == 28 then
24 break
25 end
26 end
27 end
28end
29
30-- Random Password Generator
31local charset = {} do -- [0-9a-zA-Z]
32 for c = 48, 57 do table.insert(charset, string.char(c)) end
33 for c = 65, 90 do table.insert(charset, string.char(c)) end
34 for c = 97, 122 do table.insert(charset, string.char(c)) end
35end
36
37local function randomString(length)
38 if not length or length <= 0 then return '' end
39 math.randomseed(os.clock()^5)
40 return randomString(length - 1) .. charset[math.random(1, #charset)]
41end
42
43
44--
45-- Bank Utilities
46--
47function checkAccount (userName, userPassword)
48 if fs.exists(userName) then
49 local file = fs.open (userName, "r") -- needs to be adjusted to propper file location
50 local fileData = {} -- stores file data to table
51 local line = file.readLine() -- ticking this up to read different lines
52 repeat
53 table.insert(fileData, line) -- add this line's string to table
54 line = file.readLine()
55 until line == nil -- when nil, there's nothing left
56 file.close()
57
58 local aID = fileData[1]
59 local aPassword = fileData[2]
60 local aBalance = fileData[3]
61 if aPassword == userPassword then -- if password correct, return balance
62 return aBalance
63 else -- if password incorrect, return nil
64 return nil
65 end
66 end
67end
68
69function createAccount (aName, aPassword)
70 -- init.
71 if fs.exists("bank/accounts") == false then -- check for accounts folder
72 fs.makeDir("bank/accounts") -- create it if not
73 end
74 if fs.exists("bank/accounts/"..aName) then
75 handleError("account already exists")
76 end
77
78 -- creation
79 local file = fs.open("bank/accounts/"..aName, "a") -- create file in append mode
80 file.writeLine(os.getComputerID) -- write ID to file on line 1
81 file.writeLine(aPassword) -- write password to file on line 2
82 file.writeLine("0") -- create balance and place on line 3
83 file.close() -- save file
84end