Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript User Authentication With Express and Mongo Sessions and Cookies Authenticating the Username and Password

Brian Anstett
Brian Anstett
5,831 Points

req.session is 'undefined' outside the user.authenticate() callback function

The req property session is undefined outside the user.authenticate() callback function. I've confirmed that value is being initialized inside the callback function. I've confirmed that the express-session middleware is being called before the route middleware. But after the redirect to /profile, the get route for profile does have req.session in its scope. Thanks for the help!

app.js

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var app = express();

// mongodb Connection
mongoose.connect('mongodb://localhost/bookworm', { useMongoClient: true });
var db = mongoose.connection;
//mongo error
db.on('error', console.error.bind(console, "connection error"));

//session
app.use(session( {
  secret: 'treehouse loves you',
  resave: true,
  saveUninitialized: false
}));
// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// serve static files from /public
app.use(express.static(__dirname + '/public'));

// view engine setup
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');

// include routes
var routes = require('./routes/index');
app.use('/', routes);

:
:
:

routes/index.js

:
:
router.post('/login', (req, res, next) =>{
  if(req.body.email && req.body.password){
    user.authenticate(req.body.email, req.body.password, function (error, user){
      if(error || !user){
        return next(error);
      }else{
        req.session.userId = user._id;
        console.log(req.session.userId);
        return res.redirect('/profile');
      }
    })
  }else{
    var error = new Error("Not All Fields Filled Out.");
    error.status= 401;
    next(error);
  }
});
//GET /profile
router.get('/profile', (res, req, next) => {
  console.log('profile');
  console.log(req.session);
  console.log('after');
  if(! req.session.userId){
    var error = new Error("User Not Authenticated");
    error.status = 403;
    return next(error);
  }
  user.findById(req.session.userId, function(err,user){
    if (err){
      return next(err);
    }else{
      res.render('profile',{name:user.name, favorite:user.favoriteBook});
    }  
  })
});
:
:

log output

59fb2be32ff6ba0728eb8e42
profile
undefined
after

1 Answer

Brian Anstett
Brian Anstett
5,831 Points

If you notice in the get route for profile, my req and res parameters were switches. Thanks for every one's assistance.