2016-08-20 2 views
1

저는 몽구스와 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에서이 메서드 호출에 대한 로그 메시지가없는 반면, 저장 방법은 내 사용자에 나타내는 성공적인 절약 :

//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이 매개 변수로 전달되어 callback(null, passwordData.passwordHash)으로 호출하면 실행됩니다. 오류가 발생했다면 변수로 저장할 수 있습니다 (예 : err을 함수로 전달하십시오. callback(err, null)

염분으로 돌아갑니다. 나는 당신의 튜토리얼을 읽을하지 않은 있지만 암호를 확인할 수 있도록 사용자 데이터와 함께 데이터베이스에 저장하는 것이 중요 할 때 여기

좋은 자원을 사용자가 로그인 :.

Password Hashing add salt + pepper or is salt enough?

데이터베이스에 저장 한 암호와 동일한 암호를 생성하려면 소금이 필요합니다. 소금에 접근 할 수 없다면 주어진 암호가 동일한 해시를 생성하는지 알 수 없습니다.