无法使用此分配将数据保存到MongoDB

时间:2016-10-06 08:46:41

标签: mongodb mongoose

我正在学习使用Mongo,Express,Angular和Node获取MEAN的书的MEAN堆栈。

我遵循代码并测试所有内容,但是我得到了一个没有错误的错误,在书页364中,我无法将盐和哈希保存到MongoDB。

我使用postman来测试我的代码和本书一样,我可以在postman中获得JWT,但是当我使用db.users.find()命令检查MongoDB时,只能在MongoDB上获得_id,name,email和__v。

结果如下:

"_id" : ObjectId("57f5f1a91093e2650f427081"), 
"email" : "bb7@q.com", 
"name" : "bb7", 
"__v" : 0 

我使用arch Linux和MongoDB版本是3.2.9

我想setPassword方法会导致问题,但没有错误,很奇怪。

setPassword方法是

userSchema.methods.setPassword = (password) => {
  this.salt = crypto.randomBytes(16).toString('hex');
  this.hash = crypto.pbkdf2Sync(password, this.salt, 1000,64,   'sha512').toString('hex');
};

我关于注册的整个代码是

users.js

   var mongoose = require('mongoose');
var crypto = require('crypto');
 var jwt = require('jsonwebtoken');

var userSchema = new mongoose.Schema({
  email: {
   type: String,
    unique: true,
   required: true
 },
  name: {
  type: String,
   required: true
  },
 hash: String,
  salt: String
});

 userSchema.methods.setPassword = (password) => {
  this.salt = crypto.randomBytes(16).toString('hex');
 this.hash = crypto.pbkdf2Sync(password, this.salt, 1000,64, 'sha512').toString('hex');
};

userSchema.methods.validPassword = (password) => {
  console.log('this salt  '+this.salt);
 // pbkdf2 params is password, salt, iterations, hashBytes, digest
 var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex');
  console.log('this hash '+this.hash);
 return this.hash === hash;
   };

userSchema.methods.generateJwt = () => {
  var expiry = new Date();
  expiry.setDate(expiry.getDate() + 7);

 return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
exp: parseInt(expiry.getTime() / 1000) // Unix time in seconds
 }, process.env.JWT_SECRET);
 };

mongoose.model('User', userSchema);

authentication.js

  var passport = require('passport');
 var mongoose = require('mongoose');
 var User = mongoose.model('User');

 var sendJSONresponse = (res, status, content) => {
  res.status(status);
 res.json(content);
 };

 module.exports.register = (req, res) => {

  if(!req.body.name || !req.body.email || !req.body.password) {
   sendJSONresponse(res, 400, {
      'message': "All fields required"
   });
   return;
  }

  var user = new User();

  user.name = req.body.name;
  user.email = req.body.email;

  user.setPassword(req.body.password);

 user.save((err) => {
   var token;
   if(err) {
     sendJSONresponse(res, 404, err);
   } else {
     token = user.generateJwt();
     sendJSONresponse(res, 200, {
      'token': token
     });
  }
 })
  }

 /** login */
 module.exports.login = (req, res) => {
   if(!req.body.email || !req.body.password) {
    sendJSONresponse(res, 400, {
     'message':'All fields required'
   });
  return;
 }

   passport.authenticate('local', (err, user, info) => {
    var token;

     if(err) {
      sendJSONresponse(res, 404, err);
      return;
   }

    if(user) {
       token = user.generateJwt();
     sendJSONresponse(res, 200, {
       'token': token
      });
    } else {
      sendJSONresponse(res, 401, info); // info msg about why authentication failed
     }
 })(req, res);
  };

并且github地址上的整个代码是this link

1 个答案:

答案 0 :(得分:0)

这就是我所做的:

  • 克隆回购:git clone git@github.com:simonholmes/getting-MEAN.git
  • 结帐分行:cd getting-MEAN; git checkout chapter-11
  • 设置JWT秘密:export JWT_SECRET=secret
  • 启动应用:npm start

并发送注册请求:

curl -v -X POST http://localhost:3000/api/register -d "email=user@gmail.com&password=pass&name=user"

收到回复:

{"token":"some token"}

然后检查了mongo db:

mongo
> use Loc8r
> db.users.find() 
哈希& salt与rest属性一起存储。所以不确定你有什么问题吗?如果您想在响应中获得更多属性,只需扩展register控制器中authentication方法中返回的内容:

user.save(function(err, user) {
  var token;
  if (err) {
    sendJSONresponse(res, 404, err);
  } else {
    token = user.generateJwt();
    sendJSONresponse(res, 200, {
      "token" : token,
      "email": user.email,
      "id": user._id
    });
  }
});