Search code examples
node.jsexpressauthorizationjwtexpress-jwt

How to display the Username of the currently logged in User using JWT tokens


I'm using Express/Node.js, with mongoDB. When a user login/registers, they are giving a JSON Web Token (JWT) and they are redirected to the 'homepage.hbs'. How can I display the username on the homepage of the currently logged in User?

Here is my code for logging in the user.

Auth.js

    $("#login-form").submit(function (event) {
                event.preventDefault();
                $.ajax({
                    type: 'POST',
                    url: '/users/login',
                    dataType: 'json',
                    data: {
                        'user_name': event.target.inputUsername.value,
                        'password': event.target.inputPassword.value
                    },
                    success: function(token){
                         $(location).attr('href', '/homepage' );


                    },

Index.js

router.get('/homepage', function(req, res, next) {
    try {
        var jwtString = req.cookies.Authorization.split(" ");
        var profile = verifyJwt(jwtString[1]);
        if (profile) {
            res.render('homepage');
        }
    }catch (err) {
            res.json({
                "status": "error",
                "body": [
                    "Not logged in!"
                ]
            });
        }
});

Users.js

router.post('/login', function(req, res, next){
    var username = req.body.user_name;
    var password = req.body.password;
    User.findOne({'user_name': username}, function (err, user) {

        if (err)
            res.send(err);

        if (user) {

            if (user.validPassword(password)) {

                user.access_token = createJwt({user_name: username});
                user.save();
                res.cookie('Authorization', 'Bearer ' + user.access_token); 
                res.json({'success' : 'currentlyloggedIn'});
            }
            else {
                res.status(401).send({
                    "status": "error",
                    "body": "Incorrect combination"
                });
            }
        }
        else 
          {
            res.status(401).send({
                "status": "error",
                "body": "Username not found"
            });
        } }); });


/*Creates a JWT*/
function createJwt(profile) {
    return jwt.sign(profile, 'JWT password', {
        expiresIn: '5d'
    });
}

Solution

  • If I'm understanding your problem, I think you simply need to pass some local variables to your view when you render it. For example:

    res.render('homepage', { profile })
    

    Now in your homepage template, you'll have an object called profile that contains the various user data. See the res.render Express docs for additional info.