If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To show the details of the signed-in user, we need to create a route in the server-side that will render a view containing the user details. Here are the steps to achieve this:
auth.js
file in the routes
folder. We can call it /user
.javascriptCopy code
router.get('/user', (req, res) => {
// render user details view
});
req.user.id
property. This property is set by the passport.authenticate()
middleware we added earlier. It contains the user ID of the signed-in user.javascriptCopy code
const User = require('../models/user');
router.get('/user', (req, res) => {
User.findById(req.user.id, (err, user) => {
if (err) {
console.error(err);
res.status(500).send('Server error');
} else {
res.render('user', { user });
}
});
});
User
model, we need to add a method to retrieve the user by ID.javascriptCopy code
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
// ...
});
userSchema.statics.findById = function (id, callback) {
return this.findOne({ _id: id }, callback);
};
module.exports = mongoose.model('User', userSchema);
views
folder called user.ejs
. This view file should display the user details.lessCopy code
<h1>User Details</h1>
<p>Name: <%= user.name %></p>
<p>Email: <%= user.email %></p>
/user
route to ensure that only signed-in users can access it.javascriptCopy code
const { ensureAuthenticated } = require('../config/auth');
router.get('/user', ensureAuthenticated, (req, res) => {
// ...
});
Now, when a signed-in user navigates to /user
, they will see their user details displayed in the user.ejs
view.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.