Once i register on my site, I can login fine and logout fine, and if I don't put anything into the login fields, it throws my error saying a password and email is required and i can reload the login page fine, But if i try to log in with a incorrect password, the error for that throws and says incorrect email or password, BUT once i try to click back to the login page or ANY other page on my site, in my console it says

throw er; // Unhandled 'error' event ^

TypeError: Cannot read property 'password' of null

it says the typeError is on the bcrypt.compare line.

userSchema.statics.authenticate = function(email, password, callback){
    User.findOne({email: email})
    .exec(function(error, user){
        if(error){
            callback(error)
        }else if(!user){
        const err = new Error('User not found.')    
        err.status = 401
        callback(err)
        }
        bcrypt.compare(password, user.password, function(error, result){
            if(result === true){
                return callback(null, user)
            }else{
                return callback()
            }
        })
    })

}

This is my login route

router.post('/login', (req, res, next)=>{
  if(req.body.email && req.body.password){

    User.authenticate(req.body.email, req.body.password, function(error, user){
      if( error || !user){
        const err = new Error("Email or password is incorrect.")
        err.status = 401
        next(err)
      }else{

        req.session.userId = user._id;
        res.redirect('/profile')
      }
    });

  }else{
    const err= new Error('Email and Password required.')
    err.status = 401
    next(err)
  }

})

Everything works great, the only time it crashes the server/site is when I try to log in with an INCORRECT password, then it throws the error and then after throwing the error the site crashes. If I don't put a email or password, it throws the error for that and continues to work fine, and again I can log in with the correct email and password, log out and register just fine.

Node/express is new to me, so forgive me for any rookie mistakes. I'm trying to learn how to properly debug in express/Node.js.

Thank you for any help!

1 Answers

0
mbojko On

The problematic line will be executed whether user is defined or not (and accessing undefined.password will crash the script). You can guard it with an else:

        }else if(!user){
           const err = new Error('User not found.')    
           err.status = 401
           callback(err)
        } else {
           bcrypt.compare(password, user.password, function(error, result){