im developing a small application with login and having an issue accessing session data.
nb: using express 3.0, coffee-script and mongoose
So in my app I have the following:
app.locals.use (req,res) ->
res.locals.session = req.session
res.locals.title = config.title
res.locals.href = config.href
In my login.coffee I do the following:
ModelUser.findOne {email: email, password: password}, (err, results) ->
if err then console.log err
if results?
req.session.user = results
req.session.authenticated = true
res.redirect '/'
else
req.session.error = 'bad login'
res.redirect '/'
If I go to output #{session.user}
in Jade, I get [bject,Object]
, but if I enter in "name" or "email" it returns blank. If I go into console and log the session object in the app.coffee, you can see the following:
if req.session? then console.log req.session.user
returns:
{ _id: '4f9b60ba7a7ab7e7f711920e',
email: 'foobar@gmail.com',
name: 'Demo User',
password: '078d2bf82ee269cd9577588d212655c3a2162dc5b09e7c29c6a343926ee881a9' }
But if do console.log req.session.user.email
it gives me a 500 error saying its not defined.. but I dont know why because you can see it is defined.
EDIT:
Solved; It was an async issue with the application continuing on before it got the user. Had to send a callback to the find and use next()
if req.session.authenticated
require('./lib/getUser')(req.session.uid, (results) ->
res.locals.user = results
console.log res.locals
done()
)
else
done()
There is an async issue with the application flow. The server is continuing before the results are returned, thus being undefined.