I would like to display a specific error instead of the generic "wrong credentials"
For example, if someone inserts the password but the email is right, only "password is wrong" should appear.
How can I achieve that?
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")
}
})
CodePudding user response:
To achive what you want, need first check the database to find the user with his email.
Then, if you find it you can check if password is ok, if you don't find the user you be able to send the information back.
Then if password is ok you can loged user in, if not send a message about the wrong password.
But once again, please, encrypted your password! And less information you give to an attacker, the best secured is your application.
CodePudding user response:
I recommend not displaying that "password is incorrect" because it will create a loophole in your authentication. But I have provided a code to check the password separately from its message.
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")
}
})
CodePudding user response:
you should validate individually in some function(in your case for email and password) and throw specific exceptions.
Something like this (in 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()
catch these specific exceptions in your code and throw them. This solution has db cost.