I want to set and retrieve the session from a current logged user, so I did something like this:
router.post('/login', function (req, res) {
if (JSON.stringify(req.body) == "{}") {
return res.status(400).json({ message: "corpo vazio" });
}
if (!req.body.email) {
return res.status(400).json({ message: "tem que especificar um email" });
}
if (!req.body.password) {
return res.status(400).json({ message: "tem que especificar uma password" });
}
Loja.findOne({ email: req.body.email }, function (err, loja) {
if (!loja) {
return res.status(404).json({ message: "login invalido" });
}
if (loja.password != req.body.password) {
return res.status(400).json({ message: "password invalida" });
}
if (err) {
return res.status(500);
}
// se tudo correr bem guarda a sessao do utilizador
req.session.loja = loja;
return res.send(req.session.loja);
});
});
then to retrieve the session i do something like this:
router.get('/confirm-login',function(req,res){
return res.send(req.session.loja);
});
tried it our, the first works well, it sends me a response with the full object that needs to be stored, but when I hit confirm-login at postman it send me an empty response :S, what I am doing wrong?
When you write such a route you should first check the existence of session
and stuff you've attached to it and send a proper response otherwise:
router.get('/confirm-login',function(req,res){
if ( req.session && req.session.loja ) {
res.send(req.session.loja);
} else {
res.status(401).send({ status: 'Unauthorized'});
}
});