簡體   English   中英

貓鼬的“模式方法”回調不起作用

[英]Mongoose “schema method” callback not working

我是mongoose和node.js的新手。 我嘗試遵循本教程: https : //scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications#sample-model-for-users

在入口點index.js中,我嘗試調用“ chenya.saltHashPassword(function(err,passwordHash)”。由於在user.js中可以打印出三個日志消息,因此實際上在user.js中被調用;但是,沒有日志在index.js中根本沒有調用此方法的消息,相反,save方法可以打印出指示成功保存的日志消息。

//Lets load the mongoose module in our program
var mongoose = require('mongoose');

//Lets connect to our database using the DB server URL.
mongoose.connect('mongodb://localhost:27017/server_naturis');

// if our user.js file is at app/models/user.js
var User = require('./user');

// create a new user called Chenya
var chenya = new User({
  userName: 'Chenya',
  email: 'chenya@gmail.com',
  password: 'Chenya'
});

// call the custom method. hash the password
chenya.saltHashPassword(function(err, passwordHash) { // NOT CALLED!
  if (err) {
    console.log('chenya.saltHashPassword: ' + err);
  } else {
    this.password = passwordHash;
    console.log('Your hashed password is ' + passwordHash);
  }
});

// call the built-in save method to save to the database
chenya.save(function(err) { // CALLED!
  if (err) {
    console.log('chenya.save: ' + err);
  } else {
    console.log('User saved successfully!');
  }
});

在我的user.js中,我具有模式功能“ userSchema.methods.saltHashPassword”:

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Require the crypto module for password hash
'use strict';
var crypto = require('crypto');

// create a schema
var userSchema = new Schema({
  userName: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
});

// add a schema method
/**
 * generates random string of characters i.e salt
 * @function
 * @param {number} length - Length of the random string.
 */
var genRandomString = function(length){
    return crypto.randomBytes(Math.ceil(length/2))
            .toString('hex') /** convert to hexadecimal format */
            .slice(0,length);   /** return required number of characters */
};
/**
 * hash password with sha512.
 * @function
 * @param {string} password - List of required fields.
 * @param {string} salt - Data to be validated.
 */
var sha512 = function(password, salt){
    var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
    hash.update(password);
    var value = hash.digest('hex');
    return {
        salt:salt,
        passwordHash:value
    };
};
/**
 * a function that will use the above function 
 * to generate the hash that should be stored 
 * in the database as user’s password.
 */
userSchema.methods.saltHashPassword = function() {
    var salt = genRandomString(16); /** Gives us salt of length 16 */
    var passwordData = sha512(this.password, salt);
    console.log('UserPassword = '+ this.password);
    console.log('Passwordhash = '+ passwordData.passwordHash);
    console.log('\nSalt = '+ passwordData.salt);
    return passwordData.passwordHash;
}

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);

// make this available to our users in our Node applications
module.exports = User;

終奌站:

UserPassword = Chenya
Passwordhash = 5bb5bf2181e2c713bae1eb49d1f3646b23db839368d38c33951774c92cec39a3c4b855aea30875e72cce6f271bdbdb27de8976c9316df09d086435b6c5629548

Salt = a88384d072b720de
(node:11717) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
User saved successfully!

您沒有將回調參數傳遞到userSchema.methods.saltHashPassword而是像對待功能一樣對待該函數。

userSchema.methods.saltHashPassword更改為:

userSchema.methods.saltHashPassword = function(callback) { // <-- Add callback param
    var salt = genRandomString(16); /** Gives us salt of length 16 */
    var passwordData = sha512(this.password, salt);
    console.log('UserPassword = '+ this.password);
    console.log('Passwordhash = '+ passwordData.passwordHash);
    console.log('\nSalt = '+ passwordData.salt);

    // Your function that you passed in is called here
    callback(null, passwordData.passwordHash);
}

您要回調的原因不是在saltHashPassword中調用而是在save被調用的原因是, Mongoose定義了該方法,要求該回調函數需要一個參數以獲取錯誤和實際返回值。

發生錯誤時,可以預期回調將定義錯誤處理,這是一種好習慣,也是為什么您會看到教程建議您這樣做的原因。 當您為Schema定義自己的方法時,您將不再需要該方法,而必須自己進行設置。

因此,如您在上面的函數中看到的那樣,就是這樣。 現在您將回調作為參數傳入,並使用callback(null, passwordData.passwordHash)對其進行調用。 如果發生錯誤,則可以將其保存為變量,例如err ,並將其作為callback(err, null)傳遞給函數callback(err, null)

回到鹽。 我尚未閱讀您的教程,但重要的是您將它們與用戶數據一起保存在數據庫中,以便用戶登錄時可以驗證密碼。

這里的好資源:

密碼哈希加鹽+胡椒粉還是鹽足夠?

您需要使用salt來生成與存儲在數據庫中相同的哈希密碼。 如果您無權使用該鹽,則無法確定所輸入的密碼是否會生成相同的哈希值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM