RaddyTheBrand / 25.NodeJs-Express-EJS-MongoDB--Blog

https://express-mongodb-blog.vercel.app
MIT License
93 stars 50 forks source link

Layout related doubt #6

Open ayush-848 opened 2 months ago

ayush-848 commented 2 months ago

@RaddyTheBrand I have register 2 users and I want after login the home page i.e index.ejs say "Hello, <%= username %>"

how to pass the username through both the layouts coz the "/" falls under the main.js

RaddyTheBrand commented 2 months ago

Hey Ayush, Since you already have registered users with usernames in your DB, you can include the username in the JWT token. Currently, your JWT token only includes userId and iat. You can verify that by going to jwt.io and pasting your jwt token there + your secret.

For example, in Routes -> admin.js - Admin Check Login code:

// include username

const token = jwt.sign({ 
      userId: user._id,
      username: username
 }, jwtSecret );

Now you your JWT token (when decoded) should look something like this:

{
  "userId": "66cb35559b287fc273f87c7a",
  "username": "Ayush",
  "iat": 1724593503
}

Then next step would be to decode that and display it on your home page. In Routes -> main.js include JWT and your JWT secret at the top:

const jwt = require('jsonwebtoken');
const jwtSecret = process.env.JWT_SECRET;

Then in GET Home code you can grab the token from cookies and decode it:

/**
 * GET /
 * HOME
*/
router.get('', async (req, res) => {
  const token = req.cookies.token;

  if(!token) {
    return res.status(401).json( { message: 'Unauthorized'} );
  }

  const decoded = jwt.verify(token, jwtSecret);
  const myUsername = decoded.username;

...

Then you can use "myUsername" to render send it to the page:

    res.render('index', { 
      locals,
      data,
      current: page,
      myUsername,
      nextPage: hasNextPage ? nextPage : null,
      currentRoute: '/'
    });

Finally, in your index.ejs you should have access to myUsername. <%= myUsername %>

This is one way of doing it :-) Just make sure that you re-login after you change the code so you get a new JTW token with the username.

I hope this helps!

ayush-848 commented 2 months ago

Hey Ayush, Since you already have registered users with usernames in your DB, you can include the username in the JWT token. Currently, your JWT token only includes userId and iat. You can verify that by going to jwt.io and pasting your jwt token there + your secret.

For example, in Routes -> admin.js - Admin Check Login code:

// include username

const token = jwt.sign({ 
      userId: user._id,
      username: username
 }, jwtSecret );

Now you your JWT token (when decoded) should look something like this:

{
  "userId": "66cb35559b287fc273f87c7a",
  "username": "Ayush",
  "iat": 1724593503
}

Then next step would be to decode that and display it on your home page. In Routes -> main.js include JWT and your JWT secret at the top:

const jwt = require('jsonwebtoken');
const jwtSecret = process.env.JWT_SECRET;

Then in GET Home code you can grab the token from cookies and decode it:

/**
 * GET /
 * HOME
*/
router.get('', async (req, res) => {
  const token = req.cookies.token;

  if(!token) {
    return res.status(401).json( { message: 'Unauthorized'} );
  }

  const decoded = jwt.verify(token, jwtSecret);
  const myUsername = decoded.username;

...

Then you can use "myUsername" to render send it to the page:

    res.render('index', { 
      locals,
      data,
      current: page,
      myUsername,
      nextPage: hasNextPage ? nextPage : null,
      currentRoute: '/'
    });

Finally, in your index.ejs you should have access to myUsername. <%= myUsername %>

This is one way of doing it :-) Just make sure that you re-login after you change the code so you get a new JTW token with the username.

I hope this helps!

Sure, thanks

ayush-848 commented 1 month ago

hi @RaddyTheBrand please see this https://myday-gklz.onrender.com/ I have added few extra stuffs

RaddyTheBrand commented 1 month ago

That's pretty cool! Everything seems to work quite well

ayush-848 commented 1 month ago

That's pretty cool! Everything seems to work quite well

Thanks