2016-10-26 7 views
3

オブジェクトがmongodbに保存される前にパスワードをハッシュするために、私はmongooseを使って組み込みのプリセーブフックを使用します。 しかし、更新中にハッシュを処理する正しい方法は何ですか?mongooseの更新時にパスワードをハッシュ

私はこれを更新前のフックで解決しようとしましたが、これはモデルの検証(パスワードの長さなど)をバイパスするため、いくつかの重大な欠点があります。

私のアプローチでした

(短縮):だから

userSchema.pre('findOneAndUpdate', function (next) { 
    let query = this; 
    let update = query.getUpdate(); 

    if (!update.password) { 
     return next(); 
    } 

    hashPassword(update.password, function (err, hash) { 
     //handle error or go on... 
     //e.g update.password = hash; 
    }); 
}); 

、この問題を解決するための好ましい方法は何ですか?

私は前 'save'ミドルウェア使用することになり

答えて

3

AccountSchema.pre('save', function(next) { 
    this._doc.password = encrypt(this._doc.password); 
    next(); 
}); 

しかし、これを行うことは、ドキュメントを更新するためにもsaveを使用する必要があります。

Account.findById(id, function(err, doc) { 
    if (err) return false; 
    doc.password = "baloony2"; 
    doc.save(); 
    }); 

documentation for updateに述べたように:

[...]

アップデートを使用しているときの値は、以下が適用されていない、彼らの適切な型にキャストされていますが:

  • デフォルト
  • セッター
  • バリ
  • ミドルウェア

あなたがそれらを必要とする場合機能、使用する 最初にドキュメントを取得する伝統的なアプローチ。

検証例:例の

const crypto = require('crypto'); 
const algorithm = 'aes-256-ctr'; 
const password = 'aSjlkvS89'; 

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

mongoose.connect("mongodb://localhost:33023/test_1"); 
mongoose.Promise = require('bluebird'); 

function encrypt(text) { 
    var cipher = crypto.createCipher(algorithm, password); 
    var crypted = cipher.update(text, 'utf8', 'hex'); 
    crypted += cipher.final('hex'); 
    return crypted; 
} 

// SCHEMA ------------------------------------------------- 

var AccountSchema = new Schema({ 
    name: { 
    type: String, 
    unique: true 
    }, 
    password: String 
}); 

var id; 

AccountSchema.pre('save', function(next) { 
    id = this._doc._id; 
    var pwd = this._doc.password; 
    console.log("hashing password: " + pwd); 
    this._doc.password = encrypt(pwd); 
    next(); 
}); 

// MODEL -------------------------------------------------- 

var Account = mongoose.model('Account', AccountSchema); 

// DATA --------------------------------------------------- 

new Account({ 
    name: "john", 
    password: "baloony1" 
}) 
.save() 
.then(function(res) { 
    Account.findById(id, function(err, doc) { 
    if (err) return false; 
    doc.password = "baloony2"; 
    doc.save(); 
    }); 
}); 

追加情報:

関連する問題