Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current logged in username using Passport JS?

I have created a simple user login application following an online tutorial using Node, Express and Passport. Login works correctly but I would like to get the username of the current logged in user and I can't seem to get this working.

I have the following in my app.js:

/// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');

app.use(expressSession({
  secret: 'cookie_secret',
    name: 'cookie_name',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session({
    secret: 'cookie_secret',
    name: 'cookie_name',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));

From what I read in similar posts, I need to expose the username so that I may use it in other files. I tried to do this in my app.js:

app.get('/home', function(req, res) {
  res.render('home.jade', { username: req.user.username });
});

Home is a route where I would like to use the the username, and I am trying to access the username with an alert like the following:

alert(req.user.username);

This does not work, the req object is undefined...I'm not sure what I am missing?


Managed to get this working. In my app.js I have:

app.get('/home', function(req, res) {
  res.render('home.jade', { username: req.user.username });
});

And then in my /home route I can access the username by doing:

req.user.username
like image 997
user2573690 Avatar asked Mar 21 '16 01:03

user2573690


Video Answer


2 Answers

You are mixing two things, one is the client side, and the other is the server side, both use javascript but for render server side code in the cliente side you could not use directly in the client side. you must pass to the view as you do with

app.get('/home', function(req, res) {
    res.render('home.jade', { username: req.user.username });
});

here you expose the username variable to the view

In the jade file you should do this

alert(#{username})

instead of

alert(req.user.username)
like image 111
stalin Avatar answered Oct 19 '22 22:10

stalin


try:

app.use(cookieParser());
app.use(session({
            secret: 'cookie_secret',
            name: 'cookie_name',
            proxy: true,
            resave: true,
            saveUninitialized: true
        })
    );

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

on controller use req.user

like image 34
DJeanCar Avatar answered Oct 19 '22 23:10

DJeanCar