Question

I know the policies executes before controllers, I got a problem with that, my project have the login in the index, I need to validate if the password was right, in case the password was wrong I need to show a message saying "Wrong password" but in the same index page, I am declaring a variable in policies req.session.mensaje and res.locals.mensaje, I am doing this:

This is my policy

module.exports = function(req,res,next) {
    res.locals.mensaje= '';
    if(!req.session.mensaje) return next();
    res.locals.mensaje = _.clone(req.session.mensaje);
    req.session.mensaje='';
    next();
};

This is my controller

login: function (req, res, next) {

    var username = req.param('nickname');
    var passw = req.param('password');

    User.findOneByNickname(username).exec(function(err, users) {
        if (err) {
            console.log(err);
            return next(err);
        }

        if (users){
            if(users.password===passw){
                req.session.username=users.username;
                req.session.e_mail=users.e_mail;
                res.view({user: users})
            } else { 
                req.session.mensaje='Clave invalida.';
                return res.redirect('/');
            }
        }
    });
}

config policies

'*': 'variables'

In the index the policies have not been executed, and I can't use my variable there the typeof say is undefined, but when the controller is executed and the password was right the controller takes me to the view login and there the typeof of my variable is string please help! my english is pretty poor I hope you understand me. Bless.

Was it helpful?

Solution

If I understand correctly, the issue you're running into is that the variables policy is not being run before your index page is displayed, so the mensaje variable is not available in the view. The easiest way around this is to use a controller to display the view, instead of routing to the view directly. So, in /config/routes.js, instead of:

'/': {view: 'homepage'}

or whatever you have, do:

'/': 'HomeController.index'

and in /api/controllers/HomeController.js:

index: function (req, res) {
   res.view('homepage.ejs');
}

Change the controller and view names to suit your project. The point is that by using a controller action to display the view, you can ensure that the policy will run before the view is displayed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top