Sam Williams Sam Williams - 6 months ago 67
Javascript Question

Node.js Passport Display username after successful login

I am using Node.js Passport and I'm trying to figure out how to display username after a successful login. After reading the documentation I've verified that i have Sessions and Middleware configured which is what I need but what are my next steps?

This is my users.js file:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/user');

// Home
router.get('/index', function(req, res){
res.render('index');
});
// Profile
router.get('/profile', function(req, res){
res.render('profile');
});
// Register
router.get('/register', function(req, res){
res.render('register');
});

// Login
router.get('/login', function(req, res){
res.render('login');
});

// About-us
router.get('/about-us', function(req, res){
res.render('about-us');
});


// Register User
router.post('/register', function(req, res){
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;

// Validation
req.checkBody('username', 'Username is Required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();

var errors = req.validationErrors();

if(errors){
res.render('register',{
errors:errors
});
} else {
var newUser = new User({
email:email,
username: username,
password: password,
});

User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});

req.flash('success_msg', 'You are now registered. Log In!');
res.redirect('/users/login');
}
});

passport.use(new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'User does not exist!'});
}

User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Invalid password'});
}
});
});
}));

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

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


router.post('/login',
passport.authenticate('local', {successRedirect:'/users/profile', failureRedirect:'/users/login',failureFlash: true}),
function(req, res) {
res.redirect('/users/profile')

});

router.get('/logout', function(req, res){
req.logout();

req.flash('success_msg', '');

res.redirect('/');
});

module.exports = router;


And this is my app.js file:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginandregister');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');

// Init App
var app = express();

// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');

// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public', express.static('public'));

// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));

// Passport init
app.use(passport.initialize());
app.use(passport.session());

// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;

while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));

// Connect Flash
app.use(flash());

// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});



app.use('/', routes);
app.use('/users', users);

// Set Port
app.set('port', (process.env.PORT || 3000));

app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});


I've read a similar question on the site and the answer stated that:

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


needs to be implemented. But I am confused as to where and how? I tried placing it into to my users.js file but i get a "ReferenceError: app is not defined" error in terminal when restarting the node app.
What are my next steps? Any and every help is valued and appreciated. Thank you.

EDIT:

I added

router.get('/profile', function(req, res){
res.render('profile', { username: req.user.username });
});


to my users.js file and added:

<header>
<h1>Hello?</h1>
{{#if user}}
<p>Hello {{username}}</p>
{{else}}
<p>Please <a href='/users/login'>Log In</a></p>
{{/if}}
</header>


to my profile.handlebars page but still no username display. What am i missing???

SOLUTION: Apparently my code was correct and my problem was solved hours ago however it was hiding in plain site. I am using Firefox to build my site and Chrome to conduct all my research and web searching. After DEEP searching i stumbled upon another similar question to my own and this guy complained that he had
<p>Hi, {{username}}</p>
within his index file but only
Hi
was showing up within his browser. On the contrary neither
Hi or {{username}}
was showing in my browser. My entire
<p>
tag was missing. So i simply loaded my site in Chrome and there it was problem solved! Bad practice on my part for only using one browser but that's what I get for silly mistakes :)

Answer

You need to use the rendering part of the mentioned part of this code:

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

i.e., res.render('index', { username: req.user.username }); at the right/required path.

like you can try using it as

router.get('/profile', function(req, res){
  res.render('profile', { username: req.user.username });
});

and consume(use) the rendered variable username in your view for displaying.

If this doesn't work or you have some other problem, refer Nodejs Passport display username also.

Comments