When I try to use an invaild email adress in the Login form, the app crashes saying: Cannot read properties of undefined (reading 'password').
You can see my auth.js's Login part below:
exports.login = async (req, res) => {
try {
const { email, password } = req.body;
if ( !email || !password ) {
return res.status(400).render('login', {
message: 'Please provide an email and password.'
})
}
db.query('SELECT * FROM users WHERE email = ?', [email], async (error, results) => {
console.log(results);
if( !results || !(await bcrypt.compare(password, results[0].password) ) ) {
res.status(401).render('login', {
message: 'Email or password is incorrect.'
})
} else {
const id = results[0].id;
const token = jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN
});
console.log('The token is: ' token);
const cookieOptions = {
expires: new Date(
Date.now() process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000
),
httpOnly: true
}
res.cookie('jwt', token, cookieOptions);
res.status(200).redirect("/");
}
})
} catch (error) {
console.log(error);
}
}
It should show the same line that I can see when I use an incorrect password (That part works just fine).
message: 'Email or password is incorrect.'
CodePudding user response:
If the email is invalid, the query will return an empty array, not an undefined
, meaning that your check is wrong - you should check the length of the array.
Of course, you can always leave the check that result
is defined just to be on the safe side:
if( !results || !results.length || !(await bcrypt.compare(password, results[0].password) ) ) {
res.status(401).render('login', {
message: 'Email or password is incorrect.'
});
} else {