Show Details of Signed in User

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 300:- Show Details of Signed in User

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:

  1. Create a new route in the auth.js file in the routes folder. We can call it /user.

javascriptCopy code

router.get('/user', (req, res) => {  // render user details view });

  1. In the route, we need to retrieve the user details from the database using the 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 });    }  }); });

  1. In the 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);

  1. Create a new view file in the 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>

  1. Finally, we need to add authentication middleware to the /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.

34. Manual Authentication

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support