簡體   English   中英

如何根據問題顯示特定錯誤?

[英]How can I display a specific error based on what's wrong?

我想顯示一個特定的錯誤而不是通用的“錯誤憑據”

例如,如果有人輸入了密碼,但電子郵件是正確的,則應該只顯示“密碼錯誤”。

我怎樣才能做到這一點?

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")
  }
})

要實現您想要的,首先需要檢查數據庫以使用他的電子郵件找到用戶。

然后,如果您找到它,您可以檢查密碼是否正確,如果您沒有找到用戶,您可以將信息發回。

然后,如果密碼正確,您可以登錄用戶,如果沒有,則發送有關錯誤密碼的消息。

但是,請再次加密您的密碼! 您向攻擊者提供的信息越少,最安全的是您的應用程序。

我建議不要顯示“密碼不正確”,因為它會在您的身份驗證中造成漏洞。 但是我提供了一個代碼,可以將密碼與其消息分開檢查。

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")
  }
})

您應該在某些功能中單獨驗證(在您的情況下驗證電子郵件和密碼)並拋出特定異常。

像這樣的東西(在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()

在您的代碼中捕獲這些特定異常並拋出它們。 該解決方案具有數據庫成本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM