2016-08-20 23 views
1

mongooseとnode.jsを初めて使用しました。私はこのチュートリアルに従います:https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications#sample-model-for-usersMongooseの "スキーマメソッド"コールバックが動作しない

私のエントリポイントindex.jsで、私は "chenya.saltHashPassword(function(err、passwordHash)"を呼び出そうとしましたが、実際にはuser.jsで呼び出されます。しかし、すべてでindex.jsで、このメソッドの呼び出しのためのログメッセージはありませんこれとは対照的に、保存方法が成功した貯蓄を示すログメッセージをプリントアウトすることができます。:

私のユーザーで
//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: '[email protected]', 
    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!'); 
    } 
}); 

を、3つのログメッセージをプリントアウトします。 .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! 

答えて

2

あなたは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); 
} 

Mongooseメソッドは、パラメータのために取るコールバック関数を必要とすることを規定しているため、あなたがコールバックがsaltHashPasswordに呼び出されなかっただけどsaveで呼ばれていたある理由エラーと実際の戻り値。

エラーが発生した場合、コールバックにはエラー処理が定義されていることが予想されます。これは良い習慣であり、同じことを示唆するチュートリアルが表示されるのはなぜですか? Schemaのために独自のメソッドを定義するとき、それはもはや持っておらず、自分で設定する必要があります。

上記の機能でわかるように、これが起こりました。コールバックは、callback(null, passwordData.passwordHash)でコールするパラメータとして渡され、実行されます。エラーが発生した場合は、変数として保存することができます(例: errとあなたの関数に渡しますcallback(err, null)

塩に戻る。私はあなたのチュートリアルを読んでいないが、それはときにユーザーがログインするパスワードを検証することができるように、ユーザーデータと一緒にデータベースに保存することが重要です

ここで良いのリソース:。

Password Hashing add salt + pepper or is salt enough?

データベースに保存したパスワードと同じハッシュパスワードを生成するには、塩が必要です。その塩にアクセスできない場合は、与えられたパスワードが同じハッシュを生成するかどうかを知ることはできません。

関連する問題