如何根据错误显示特定错误?



我想显示一个特定的错误,而不是一般的"错误的凭据">

例如,如果有人插入了密码,但电子邮件是正确的,只有"密码错误";应该出现。

我怎么才能做到呢?

app.post('/login', async (req, res) => {
const client = new MongoClient(url)
const data = req.body.formData
try {
await client.connect()
const database = client.db("data")
const collection = database.collection("utenti")
const result = await collection.findOne({
email: data.email,
password: data.password
})
console.log(result)
if (result.email && result.password) {
res.status(200).send("Success")
}
} catch (err) {
res.status(400).send("Wrong credentials")
}
})

要实现您想要的,首先需要检查数据库以找到具有其电子邮件的用户。

然后,如果您找到它,您可以检查密码是否正确,如果您没有找到用户,您可以将信息发送回去。

如果密码正确,则可以登录用户,如果密码不正确,则发送密码错误的消息

但是,再一次,请加密您的密码!你给攻击者的信息越少,你的应用程序就越安全。

我建议不要显示" password is incorrect " "因为这会给你的身份验证带来漏洞。但是我已经提供了一个代码来单独检查密码和它的消息。

app.post('/login', async (req, res) => {
const client = new MongoClient(url)
const data = req.body.formData
try {
await client.connect()
const database = client.db("data")
const collection = database.collection("utenti")
const email = await collection.findOne({
email: data.email,
})

console.log("email is correct", email);
if (!email) {
res.status(400).send("Your email is incorrect")
}
const password = await collection.findOne({
password: data.password,
});
if (email && password) {
res.status(200).send("Success")
}
if (!password) {
res.status(400).send("Only Email is correct and password is incorrect", email);
}
} catch (err) {
res.status(400).send("Wrong credentials")
}
})

您应该在某些函数中单独验证(在您的示例中为email和password)并抛出特定的异常。

像这样(在python中):

fun validate_email_password(email, password):
email = db.findByEmail(email)
if not email:
throw EmailNotFound()
password = db.findByPassword(password)
if not password:
throw passwordNotFound()

在代码中捕获这些特定的异常并抛出它们。此方案有db成本。

相关内容

最新更新