Martin Nordström
Martin Nordström

Reputation: 6025

Object not defined when using await

I am currently trying to add some authentication to my node API.

Right now I'm using PassportJS (pretty new to this so sorry for my incompetents).

I am trying to add a local strategy and check if the users password is legit when loggin in:

// Local Strategy
passport.use(
  new LocalStrategy(async (username, password, done) => {
    try {
      // Find user by username
      const user = await User.findOne({ username })

      // No user found
      if (!user) {
        return done(null, false)
      }
      console.log('user', user) // Getting output

      // Check if password correct
      const isMatch = await user.isValidPassword(password)

      // Handle if password is not correct
      if (!isMatch) {
        return done(null, false)
      }

      // Return user
      done(null, user)
    } catch (err) {
      done(err, false)
    }
  })
)

Something I've noticed is when using await on const isMatch = await user.isValidPassword(password) Postman is saying: Error: ReferenceError: user is not defined. And when I remove await it works fine, but I can type in the wrong password but I still can login. And I can see my user object when I console.log it.

{
    "username": "martinnord3",
    "password": "this_is_the_wrong_password"
}

Here's the isValidPassword function:

UserSchema.methods.isValidPassword = async function(newPassword) {
  try {
    return await bcrypt.compare(newPassword, user.password)
  } catch (err) {
    throw new Error(err)
  }
}

I guess there's something obvious I'm missing, but I can't manage to solve this.

Thanks for taking your time to read this!

Upvotes: 0

Views: 46

Answers (1)

Martin Nordström
Martin Nordström

Reputation: 6025

Well this is a bit awkward, but I guess it's my duty to answer my own dumb question... My function isValidPassword has this: ...user.password and I don't specify what user is in that function.. It expects this.

Upvotes: 1

Related Questions