Step 17
We can apply the same pattern to the homepage! If a user is already logged in, then take them to their dashboard and skip the log in form.
app.get("/", (req, res) => {
const username = req.cookies.username;
const message = req.cookies.message;
if (username) {
res.redirect("/dashboard");
} else {
res.render("index.njk", { message });
}
});
Save the index.js
file; visit the homepage and login with a valid credentials. Then, try to visit the homepage again! You must be redirected to dashboard.
Now we can also implement the logout process; we simply remove (clear) the username cookie:
app.post("/logout", (req, res) => {
console.log(colors.cyan("Log out!"));
res
.clearCookie("username")
.cookie("message", "You have successfully logged out!")
.redirect("/");
});
Save the index.js
file. Play around with the application; log in and out, try to visit dashboard when you are already logged in or after you have logged out. The app is coming together 😃.