Step 7
Let's check user credentials as they login.
Update route handler for POST /login
in index.js
:
app.post("/login", async (req, res) => {
const username = req.body.username;
const password = req.body.password;
console.log(colors.cyan("Login using", { username, password }));
try {
// check credential
const user = await users.findOne({ username, password });
if (!user) throw Error("No user found with this username!");
console.log(user);
// redirect to dashboard
res.redirect(`/dashboard?username=${user.username}`);
} catch (err) {
console.log(err);
// redirect to homepage
res.redirect("/");
}
});
Notice if we don't have a user registered in our database with the provided credentials we redirect to the login page. This could be confusing for clients when e.g. they misspell their username or input an incorrect password, there must be an error message shown to them.
Save index.js
and try to login using a valid (and then invalid) credentials.