First question on Stackoverflow, still new to programming.
I'm trying to make a simple bank login page with a JSON file that has all usernames and passwords in it.
I'm making an if statement that will read the JSON file to find the username and password as a key and value to match the user's input on the website. If it matches the input, it will login to the website, otherwise, it will either say "Invalid Password" or "Not a registered Username".
What's happening is that it keeps giving me "Not a registered email" when I typed the correct username and password but I want to login with the correct username and password.
I'm using node.js and express (not sure if it matters?). Sorry if my code or explanation isn't clear, still very new.
...
var accounts = JSON.parse(fs.readFileSync('./accounts.json'));
app.post('/', function (req, res) {
username1 = req.body.userinput; //username is their email
password1 = req.body.passinput;
if (username1 == accounts.email && password1 == accounts.password) {
console.log("Correct login");
res.render('login', { layout: false});
}
else if (username1 == accounts.email && password1 != accounts.password) {
var incorrectp = ("Invalid Password");
res.render('login', { layout: false, wrongp: incorrectp });
}
else if (username1 != accounts.email) {
var incorrectu = ("Not a registered username");
res.render('login', { layout: false, wrongu: incorrectu });
}
});
accounts.json
[
{
"id": "100001",
"email":"[email protected]",
"password":"helloworld",
"accountType":"Chequing",
"accountBalance":0
},
{
"id": "100002",
"email":"[email protected]",
"password":"lennon",
"accountType":"Savings",
"accountBalance":0
}
]
...
CodePudding user response:
You would want to iterate through accounts.json.
Try something like this.
let acc;
for (const account of accounts) {
if (username1 == account.email) {
acc = account;
}
}
if (acc == null) {
var incorrectu = ("Not a registered username");
res.render('login', { layout: false, wrongu: incorrectu });
return;
}
// Do your account checking logic here
CodePudding user response:
This approach won't scale very good. You can do this using forEach:
let accountName;
accounts.forEach(obj => {
if (obj.email === username1 && obj.password === password1) {
accountName = obj.email
})
or by using find:
const accountName = accounts.find(obj => (obj.email === username1 && obj.password === password1))
Besides the actual question, I want to emphasize that you should never store password in clear or encrypted form. A password hashing mechanism must be used, possible candidates include: Argon2, bcrypt or PBKDF2. Make sure you use appropriate parameters for these mechanisms.
