My Problem
I’m using Express/Passport to create a login system.
My problem is very simple but every time I try something I get undefined errors. I’m trying to figure out how I can pass my req.body.username
to my navbar so that it:
- Displays the username
- Display either the
logout
or theregister
/login
buttons, depending if the user is logged in or not.
I know that I will need to use an if statement inside my navbar ejs only like I said, every time I try something like:
<%if (req.body.username) { %>
<!--Logout-->
<li><a href="/users/logout">Logout</a></li>
<% }else{ %>
<!--Sign In/Register-->
<li><a href="/users/register">Register</a></li>
<li><a href="/users/login">Login</a></li>
<%}%>
… I get undefined errors.
Please help me understand what I’m doing wrong and how I can fix my code.
My Code
app.js
// setup session
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
})
);
// initialize passport
app.use(passport.initialize());
// use passport to deal with session
app.use(passport.session());
app.use(function (req, res, next) {
res.locals.isAuthenticated = req.isAuthenticated();
next();
});
userController.js
exports.register = function (req, res, next) {
if (req.isAuthenticated()) {
res.redirect("/");
} else {
res.render("register");
}
};
exports.login = function (req, res, next) {
if (req.isAuthenticated()) {
res.redirect("/");
} else {
res.render("login");
}
};
exports.register_account = async (req, res) => {
try {
const registerUser = await User.register(
{ username: req.body.username },
req.body.password
);
if (registerUser) {
passport.authenticate("local")(req, res, function () {
res.redirect("/");
});
} else {
res.redirect("/register");
}
} catch (err) {
res.send(err);
}
};
exports.login_account = (req, res) => {
// Create new user object
const user = new User({
username: req.body.username,
password: req.body.password,
});
// Check if credentials are correct
req.login(user, (err) => {
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/");
});
}
});
};
exports.logout = function (req, res, next) {
req.logout(function (err) {
if (err) {
return next(err);
}
res.redirect("/");
});
};
users.js
/// USER ROUTE ///
router.get("/register", user_controller.register);
router.get("/login", user_controller.login);
// register user in DB
router.post("/register", user_controller.register_account);
// login user
router.post("/login", user_controller.login_account);
// Logout user
router.get("/logout", user_controller.logout);
module.exports = router;
navbar.js
<ul class="navbar">
<p>USER PANEL</p>
<!--Logout-->
<li><a href="/users/logout">Logout</a></li>
<!--Sign In/Register-->
<li><a href="/users/login">Login</a></li>
<li><a href="/users/register">Register</a></li>
</ul>