[英]Making a login page using JSON as verification
关于 Stackoverflow 的第一个问题,对编程来说还是个新手。
我正在尝试使用包含所有用户名和密码的 JSON 文件制作一个简单的银行登录页面。
我正在做一个 if 语句,它将读取 JSON 文件以查找用户名和密码作为键和值以匹配用户在网站上的输入。 如果匹配输入,它将登录网站,否则,它将显示“无效密码”或“未注册的用户名”。
发生的情况是,当我输入正确的用户名和密码但我想使用正确的用户名和密码登录时,它一直给我“不是注册的电子邮件”。
我正在使用 node.js 和快递(不确定是否重要?)。 对不起,如果我的代码或解释不清楚,仍然很新。
...
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 });
}
});
帐户.json
[
{
"id": "100001",
"email":"helloworld@gmail.com",
"password":"helloworld",
"accountType":"Chequing",
"accountBalance":0
},
{
"id": "100002",
"email":"john@beatles.uk",
"password":"lennon",
"accountType":"Savings",
"accountBalance":0
}
]
...
您可能想要遍历accounts.json。
尝试这样的事情。
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
这种方法不会很好地扩展。 您可以使用 forEach 执行此操作:
let accountName;
accounts.forEach(obj => {
if (obj.email === username1 && obj.password === password1) {
accountName = obj.email
})
或使用查找:
const accountName = accounts.find(obj => (obj.email === username1 && obj.password === password1))
除了实际问题之外,我想强调的是,您永远不应该以明文或加密形式存储密码。 必须使用密码散列机制,可能的候选者包括:Argon2、bcrypt 或 PBKDF2。 确保为这些机制使用适当的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.