-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserLog.js
executable file
·73 lines (56 loc) · 1.32 KB
/
UserLog.js
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
var fs = require("fs");
var usersArr;
try {
usersArr = JSON.parse(fs.readFileSync("./users.json"));
} catch (e) {
usersArr = [];
}
//Check if user exists, if so return that user
function userExists (username) {
for (var i = 0; i <usersArr.length; i++){
if(usersArr[i].username === username){
return usersArr[i];
}
}
return undefined;
}
//Check that username and password match a user in our database.
function checkLogin (username, password){
var user = userExists(username);
if(user && user.password === password){
return true;
}
return false;
}
//Refister a new user, confirm registration was successful, check that username is unique
function registerUser(username, password) {
if(userExists(username) || username == undefined || username == " " || password == undefined) {
return false;
}
//Store users in object
usersArr.push({
username: username,
password: password
});
//Save users as JSON
saveAllUsers();
return true;
}
//Convert array of users into a JSON string, save it
function saveAllUsers(){
fs.writeFile(
"./users.json",
JSON.stringify(usersArr),
function(err){
if (err) {
console.log(err);
}
});
}
//Functions as properties on an object
module.exports = {
userExists : userExists,
checkLogin: checkLogin,
registerUser : registerUser,
saveAllUsers : saveAllUsers
};