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

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

Layout related doubt #6

Open ayush-848 opened 3 weeks ago

ayush-848 commented 3 weeks 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 weeks 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 weeks 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