在猫鼬用户验证方面需要帮助

时间:2019-02-24 00:32:38

标签: node.js mongodb authentication mongoose

我是mongoDB和mongoose的新手。但是我想做的是能够通过他们的电子邮件对我存储在数据库中的用户进行身份验证,如果成功检索到用户,我将把他们编写的密码与存储在数据库中的哈希密码进行比较

这就是我的架构

UserSchema

var UserSchema = new Schema({
  firstName: { type: String, required: true }, //require makes it so that the fields can't be left blank
  lastName: {type: String, required: true},
  emailAddress: {type: String, required: true},
  password: {type: String, required: true}      
});
var User = mongoose.model("User", UserSchema);

我在我的routes.js文件中使用basic-auth软件包,以便在邮递员中测试此api,该中间功能检查用户密码是否与邮递员的authorizatio标头上的用户密码匹配,以及与要求中的密码是否匹配.body

//This middle-where function will authenticate users
const authenticateUser = (req, res, next) => {
  let message = null;

  // Parse the user's credentials from the Authorization header.
  const credentials = auth(req);

  // If the user typed the Authorization header...
  if (credentials) {
    console.log(credentials)
    // Attempt to retrieve the user from the data store
    // by their email (i.e. the user's "key"
    // from the Authorization header).
    const user = User.find({emailAddress: credentials.name}) 

    // If a user was successfully retrieved from the data store...
    if (user) {
      // Use the bcryptjs npm package to compare the user's password typed
      // (from the Authorization header) to the user's password sent in req.body in postman
      const authenticated = bcryptjs
        .compareSync(credentials.pass, req.body.password);
      // If the passwords match...
      if (authenticated) {
        console.log(`Authentication successful for user: ${req.body.firstName} `);

        // Then store the retrieved user object on the request object
        // so any middleware functions that follow this middleware function
        // will have access to the user's information.
        req.currentUser = user;
      } else {
        message = `Authentication failure for user:  ${req.body.firstName} `;
      }
    } else {
      message = `User not found for email: ${credentials.name}`;
    }
  } else {
    message = 'Auth header not found';
  }

  // If user authentication failed...
  // Return a response with a 401 Unauthorized HTTP status code.
  if (message) {
    console.warn(message);

    // Return a response with a 401 Unauthorized HTTP status code.
    res.status(401).json({ message: 'Access Denied' });
  } else {
    // Or if user authentication succeeded...
    // Call the next() method.
    next();
  }
};

这是我吸引用户的途径

//GET /api/users 200, THIS WORKS IN POSTMAN
//This Route returns the currently authenticated user
router.get('/users', authenticateUser, (req, res) => {
  //within the route handler, the current authenticated user's information is retrieved from the Request object's currentUser property:
  const user = req.currentUser;
//we use the Response object's json() method to return the current user's information formatted as JSON:
  res.json({
    firstName: user.firstName

  });
});

我真正遇到麻烦的地方是身份验证,当我尝试使用正确的凭据登录邮递员时,在终端Authentication failure for user中遇到此错误,有人可以提供帮助,这是我的仓库{{3 }}

2 个答案:

答案 0 :(得分:0)

似乎您正在将请求中解析的密码与从请求正文中获取的密码进行比较:

    if (user) {
      // Use the bcryptjs npm package to compare the user's password typed
      // (from the Authorization header) to the user's password sent in req.body in postman
      const authenticated = bcryptjs
        .compareSync(credentials.pass, req.body.password);

我想您想要的是将标头中的密码与用户中存储的哈希值进行比较

    if (user) {
      // Use the bcryptjs npm package to compare the user's password typed
      // (from the Authorization header) to the user's password sent in req.body in postman
      const authenticated = bcryptjs
        .compareSync(credentials.pass, user.password);

答案 1 :(得分:0)

迟到总比不到好 :),所以你应该在查询之前使用 await 或者像这样使用 .then .catch

const user = await User.find({emailAddress: credentials.name}) 

之后你应该比较 db(user.password) 中的密码和 body 中的密码

const authenticated = bcryptjs.compareSync(user.password, req.body.password);

或使用

const authenticated = await bcryptjs.compare(user.password, req.body.password);