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

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

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

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?