Sunday, 7 May 2017

Redirect if successful login and access to req.user object (passport) in Handlebars

I'm implementing an user token based access in Node.js with MongoDB express and passport.js

I get the user token via /usuarios/auth/login, I place it in localStorage and send in later request in headers for private routes. Passport creates the req.user object (I know because in later requests via Postman I'm able to send the response adding the req.user object, and I also can see it in VSCode Debugger). This means Passport serializeUser and deserializeUser functions and its strategy work fine within my createToken() function

But now I want to redirect to a Handlebarstemplate when user gets a successful login, and I want to be able to access to req.user object in Handlebars. I only tried to pass user obj to handlebars but it didn't work, didn't try to redirect after a successful login, this is the second thing I want to know.

This is a piece of my code:

Express configuration:

module.exports.initMiddlewares = (app) => {
  app.engine('.hbs', hbs({
    defaultLayout: 'default',
    extname: 'hbs'
}));

app.set('view engine', '.hbs');
app.use(express.static("views"));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(session({
    secret:config.secretSession,
    store:mongoStore
}));
app.use(auth.initialize());
app.use(passport.session());

app.use(expressValidator());
routes(app);//
}

Handlebars routes:

router.get("/login", (req, res) => {//Login view
    res.render('login')
});
router.get("/registro", (req, res) => {//register view
    res.render('registro')
});
router.get("/dashboard", (req, res) => {//Dashboard
    res.render('dashboard', { usuario: req.user })//here req.user is undefined and in hbs template user attributes are blank
});

Login function in users controller. returns the token and a message and after this, req.user is created by passport

  login: (req, res, next) => {
    req.sanitize('email').trim();
    req.sanitize('password').trim();
    auth.login(req, res, next);
    req.getValidationResult()
        .then(result => {
            if (!result.isEmpty()) {
                return res.status(422).send({errores: result.useFirstErrorOnly().array()});
            }

            Usuario.findOne({email: req.body.email}, (err, usuario) => {
                if (err) return res.status(500).send({error: `Error del servidor ${err}`});
                if (!usuario) return res.status(404).send({error: "El usuario no existe"});
                if (Usuario.isPassword(req.body.password, usuario.password)) {
                    res.status(200).send({
                        message: "Te has logueado correctamente",
                        token: auth.createToken(usuario) //This works fine
                    })
                } else {
                    return res.status(404).send({error: "ContraseƱa incorrecta"})
                }
            });


        })

},

Users routes:

router.get("/", auth.authenticate(),(req, res,next) => {//This is route for authenticated users. In postman works fine when I set the token in headers
    controladorUsuario.getUsuarios(req, res);        

});
router.post("/auth/signup", (req, res) => {//new user (register)
     controladorUsuario.signup(req, res);
});
router.post("/auth/login", (req, res) => {//Login
     controladorUsuario.login(req, res);
});

controladorUsuario.getUsuarios(req, res) function, call by GET /usuarios/:

getUsuarios: (req, res) => {
    Usuario.find({}, (err, usuarios) => {
        if (err) return res.status(500).send({error: `Error del servidor ${err}`});
        if (!usuarios) return res.status(404).send({error: `No existen usuarios`});
        res.status(200).send({usuarios, usuario:req.user})//This works fine and send back the req.user
    });
},

After login, I'm able to send req.user object in responses in my API (Just doing this to try if req.user is created): what I have to do to pass it to Handlebars? what I have to do to redirect to a specific path?

AJAX requests works fine with token in header.

Thanks a lot!



via Pablo Mora

No comments:

Post a Comment