nodejs display username to all pages when logged in

Viewed 294

I am just experiencing in node.js and feeling a bit confused. I want to display username to all pages when it is logged in. I can get user id using jsonwebtoken. I am using MySQL. Here is my route

const express = require('express');
const router = express.Router();
const { requireAuth, checkUser } = require('../middleware/authMiddleware');

router.get('*', checkUser);

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

I wrote middleware code here

const checkUser = (req, res, next)=>{
    const token = req.cookies.jwt;
    if(token){
        jwt.verify(token, process.env.JWT_SECRET, async (err, decodedToken)=>{
            
            if(err){
                console.log(err.message);
                res.locals.user = null;
                next();
            }
            else{
                res.locals.user = WHAT SHOULD I ASSIGN HERE;
                next();
            }
            
        })
    }
    else{
        res.locals.user = null;
        next();
    }

}


module.exports = { checkUser};

I should assign username to res.locals.user right? How to get it?

1 Answers

If the user details is available while creating the jwt token then you should assign the decodedToken in res.local.user

const checkUser = (req, res, next)=>{
    const token = req.cookies.jwt;
    if(token){
        jwt.verify(token, process.env.JWT_SECRET, async (err, decodedToken)=>{
            
            if(err){
                console.log(err.message);
                res.locals.user = null;
                next();
            }
            else{
                res.locals.user = decodedToken;
                next();
            }
            
        })
    }
    else{
        res.locals.user = null;
        next();
    }

}


module.exports = { checkUser};

But while creating the token your process should be like below:

let userDetails = {
    id: 1,
    username: "sariful",
    email: "helloworld@website.com"
    ...
};
jwt.sign(userDetails, process.env.JWT_SECRET, function () {
   ...
});

In jwt, when creating the token it encrypts all the data that passed in jwt.sign. and when you decode the token in jwt.verify you get the decoded details that presents in the token.

PS:

you shouldn't use router.get('*', checkUser); as middleware rather you should use app.use(checkUser)

Related