使用 express 的用户身份验证错误不起作用

时间:2021-01-10 13:15:57

标签: express authentication jwt bcrypt

所以我在后端使用 express 验证用户登录时遇到了问题。如果我做一个简单的 res.send 我可以在邮递员那里得到回复。但是如果我检查用户和密码是否检查并生成令牌,如果说错误 401 无效的用户名和密码。请注意令牌可用于注册和更新配置文件。我还附加了用户架构。 简单的方法

const authUser = asyncHandler(async (req, res) => {
  const { email, password } = req.body
  res.send({ email, password })
})

enter image description here

当我尝试检查并生成令牌时

const authUser = asyncHandler(async (req, res) => {
  const { email, password } = req.body
  const user = await User.findOne({ email })

  if (user && (await user.matchPassword(password))) {
    res.json({
      _id: user._id,
      name: user.name,
      email: user.email,
      isAdmin: user.isAdmin,
      token: generateToken(user._id),
    })
  } else {
    res.status(401)
    throw new Error('Invalid Email or password')
  }
})

enter image description here

这里也是我使用 mongoose 的用户架构,并添加了一个功能来检查密码,因为在数据库中它是使用 bcrypt.js 加密的

import mongoose from 'mongoose'
import bcrypt from 'bcryptjs'

const userSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    isAdmin: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  {
    timestamps: true,
  }
)

userSchema.methods.matchPassword = async function (enteredPassword) {
  return await bcrypt.compare(enteredPassword, this.password)
}

const User = mongoose.model('User', userSchema)

export default User

1 个答案:

答案 0 :(得分:0)

你看,你的代码是绝对正确的,但前提是你首先在你的模型中正确地保存了用户。此外,存储过程中使用的密码以相同的方式从相同的模块进行哈希处理。

现在您必须更改您的检查条件,因为数据库中可能没有真正使用此电子邮件的用户来匹配您的密码并返回真实值。

import mongoose from 'mongoose'
import bcrypt from 'bcryptjs'

const userSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    isAdmin: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  {
    timestamps: true,
  }
)

userSchema.pre('save', function (next) {
  if (this.password) {
        bcrypt.hash(this.password, bcrypt.genSaltSync(15), (err, hash) => {
            if (err) console.log(err);
            this.password = hash;
            next();
        });
    }
}

userSchema.methods.Save = async (data) => {
    let model=new User(data)
    await model.save();
}

userSchema.methods.matchPassword = async function (enteredPassword) {
  return await bcrypt.compare(enteredPassword, this.password)
}

const User = mongoose.model('User', userSchema)

export default User

并更新此代码:

const authUser = asyncHandler(async (req, res) => {
  const { email, password } = req.body
  const user = await User.findOne({ email })

  if (user) {
    if(await user.matchPassword(password)) {
      res.json({
        _id: user._id,
        name: user.name,
        email: user.email,
        isAdmin: user.isAdmin,
        token: generateToken(user._id),
      })
    } else {
      res.status(401)
      throw new Error('Invalid password')
    }
  } else {
    res.status(401)
    throw new Error('Invalid Email')
  }
})

现在您知道工作的哪个部分出了问题。无用户或无腕密码