比较时密码返回假

时间:2020-01-21 06:00:37

标签: mongoose graphql bcrypt

当我保存密码时,我执行bcryp.hash并将其保存在数据库中,例如“ 1234” =>(d1c8912e41fe7ae8f44717c0a2157ab9377b14a7),但是登录时我使用bcrypt.compare返回false

添加用户

user: async (_, { input:{firstName, lastName, email, fullName, age, role, login, passwordHash} }, { models: { users } }) => {
      let user

      try {
        user = await users.create({
          firstName,
          lastName,
          email,
          fullName,
          age,
          role,
          login,
          passwordHash: await bcrypt.hash(passwordHash, 10)
        })
      } catch (error) {
        console.error(error)
      }
      return user
    }

登录用户

login: async (_, { input: { email, passwordHash } }, { models: { users } }) => {
      const user = await users.findOne({ email })

      if (!user) {
        throw new Error('No user with that email')
      }
      const valid = await bcrypt.compare(passwordHash, user.passwordHash)
       if (!valid) {
         throw new Error('Incorrect password')
       }

       //return json web token
      return jsonwebtoken.sign(
        { id: user._id, email: user.email, role: user.role },
        process.env.JWT_SECRET,
        { expiresIn: '1d' }
      )
    }

0 个答案:

没有答案