我想顯示一個特定的錯誤而不是通用的“錯誤憑據”
例如,如果有人輸入了密碼,但電子郵件是正確的,則應該只顯示“密碼錯誤”。
我怎樣才能做到這一點?
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")
}
})
uj5u.com熱心網友回復:
要實作您想要的,首先需要檢查資料庫以使用他的電子郵件找到用戶。
然后,如果您找到它,您可以檢查密碼是否正確,如果您沒有找到用戶,您可以將資訊發回。
然后,如果密碼正確,您可以登錄用戶,如果沒有,則發送有關錯誤密碼的訊息。
但是,請再次加密您的密碼!您向攻擊者提供的資訊越少,最安全的是您的應用程式。
uj5u.com熱心網友回復:
我建議不要顯示“密碼不正確”,因為它會在您的身份驗證中造成漏洞。但是我提供了一個代碼,可以將密碼與其訊息分開檢查。
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")
}
})
uj5u.com熱心網友回復:
您應該在某些功能中單獨驗證(在您的情況下驗證電子郵件和密碼)并拋出特定例外。
像這樣的東西(在python中):
fun validate_email_password(email, password): email = db.findByEmail(email) 如果不是 email: throw EmailNotFound() password = db.findByPassword(password) if not password: throw passwordNotFound()
在您的代碼中捕獲這些特定例外并拋出它們。該解決方案具有資料庫成本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/484558.html
標籤:javascript 节点.js 反应
