PythonCoder1981
PythonCoder1981

Reputation: 463

Mongoose Password Compare

I have a node.js login form that should get the user name validate that is exists. Then is should compare it to the hashed Password I have generated. I am able to register new users to the mongodb database correctly. I am also able to findOne() user. But I am unable to compare the passwords.

app.post('/login-users', async (req, res) =>{
   const user = User.findOne({name: req.body.name}, function(err, user){
       console.log('User Found')
   })
  
   try{
    if(await bcrypt.compare(req.body.password, user.password)){
      res.redirect('/')
    } else{
        console.log('Not Allowed')
    }
 } catch {
     res.status(500).send()
 }

})

Upvotes: 2

Views: 2529

Answers (2)

Code Coder
Code Coder

Reputation: 1

You can also this in the mongoose schema using schema.method

userSchema.method('validatePassword', async function (password) {
    const isValid = await bcrypt.compare(password, this.password)
    return isValid
})

Now you can call this method using

const user = await User.findById('1234567890');
const isMatch = await user.validatePassword('password');

Upvotes: 0

knicholas
knicholas

Reputation: 530

you need to move your try catch to the callback because user is an unresolved promise

app.post('/login-users', async (req, res) =>{
   const user = User.findOne({name: req.body.name},async function(err, user){
       console.log('User Found')
        try{
           if(await bcrypt.compare(req.body.password, user.password)){
            res.redirect('/')
           } else{
            console.log('Not Allowed')
           }
       } catch {
         res.status(500).send()
        }
   })
})

or wait for promise to resolve

app.post('/login-users', async (req, res) =>{
   const user = await User.findOne({name: req.body.name})
   try{
    if(await bcrypt.compare(req.body.password, user.password)){
      res.redirect('/')
    } else{
        console.log('Not Allowed')
    }
   } catch {
     res.status(500).send()
 }

})

Upvotes: 1

Related Questions