Search code examples
node.jsexpressmodel-view-controllerpassport.js

controller isnt working as it is supposed to


I used MVC to make a NodeJS server and this is one of the controllers:

module.exports.create_user = async function (req, res) {
    // console.log(req.body);
    // console.log(req.user);
    await Company.findOne({ user: req.body.user }, function (err, user) {
        if (user) {
            return res.redirect('/login');
        }
        else {
            if (req.body.password == req.body.confirm_password) {
                Company.create({
                    "country": req.body.country,
                    "username": req.body.user,
                    "password": req.body.password
                });
            }
            else {
                console.log('Passwords didnt match');
            }
        }
    });
    req.session.save(() => {
        return res.redirect('/profile');
    })
}

What this code supposed to do?

It searches if a user already exists; if yes, it will redirect to /login. If no such user exists, it should create a new user and redirect to /profile.

What does this code do?

Regardless of whether the user exists or not, the code always redirects to /login. Also, a user is created in the database, so every time a new user wants to signup, the user needs to signup and then go to sign in to get access to /profile

What is the problem here which doesn't allow redirect to /profile? And how to fix it? Let me know if you need anything else


Solution

  • passport.checkAuthentication = async function (req, res, next) {
        console.log(req.user);
        let auth_status = await req.isAuthenticated() ? "sucess" : "failure";
        console.log(`Authentication ${auth_status}`);
        // if the user is signed in, then pass on the request to the next function(controller's action)
        if (await req.isAuthenticated()) {
            return next();
        }
    
        // if the user is not signed in
        return res.redirect('/login');
    }
    

    I did a but more work on this and possibly the controller is working fine and the problem could be in middleware. In the signup case discussed above, the middelware always logs 'Authentication failure' to console.