比较密码BcryptJS [英] Compare passwords BcryptJS

查看:71
本文介绍了比较密码BcryptJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试建立一个非常基本的用户登录名.我正在尝试创建一个用户,然后使用这些凭据登录并获取JSON Web令牌.我遇到的困难是尝试比较密码,然后发送响应.

So I'm trying to build a very basic user login. I'm trying to create a user, then login with those credentials and get back a JSON Web Token. Where I'm stuck is trying to compare the passwords then send a response.

步骤:

创建用户:

  1. 输入电子邮件和密码
  2. 盐/哈希用户密码
  3. 将用户存储到数据库中
  4. 返回成功

登录

  1. 通过请求电子邮件值查找用户
  2. 如果发现比较密码
  3. 密码可以很好地发送JSON Web令牌

用户模型

email:{ 
  type: String,
  required: true,
  unique: true
},
password: {
  type: String,
  required: true
}

用户路线

var express     = require('express');
var router      = express.Router();
var jwt         = require('jsonwebtoken');
var bcrypt      = require('bcryptjs');

// Create User
...
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("superSecret", salt, function(err, hash) {
      user.password = hash;
      user.save();
      res.json({success: true, message: 'Create user successful'});
    });
  });
...

// Login
...
bcrypt.compare(req.body.password, 'superSecret', function(err, res) {
  if(req.body.password != user.password){
    res.json({success: false, message: 'passwords do not match'});
  } else {
    // Send JWT
  }
});

所以这里的两个问题是,我无法发送响应,也无法比较密码.只是完全停留在此,任何帮助将不胜感激.

So the two problems here is that, I can't send a response nor can I compare the password. Just completely stuck on this, any help would be greatly appreciated.

推荐答案

doc ,您应该这样使用 bcrypt.compare :

bcrypt.compare(req.body.password, user.password, function(err, res) {
  if (err){
    // handle error
  }
  if (res)
    // Send JWT
  } else {
    // response is OutgoingMessage object that server response http request
    return response.json({success: false, message: 'passwords do not match'});
  }
});

这是关于用猫鼬进行密码身份验证的不错的帖子(第1部分):bcrypt

这篇关于比较密码BcryptJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆