栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

猫鼬密码哈希

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

猫鼬密码哈希

mongodb博客上有一篇很棒的文章,详细介绍了如何实现用户身份验证。

http://blog.mongodb.org/post/32866457221/password-authentication-with-
mongoose-part-1

直接从上面的链接复制以下内容:

用户模型

var mongoose = require('mongoose'),    Schema = mongoose.Schema,    bcrypt = require('bcrypt'),    SALT_WORK_FACTOR = 10;var UserSchema = new Schema({    username: { type: String, required: true, index: { unique: true } },    password: { type: String, required: true }});UserSchema.pre('save', function(next) {    var user = this;    // only hash the password if it has been modified (or is new)    if (!user.isModified('password')) return next();    // generate a salt    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {        if (err) return next(err);        // hash the password using our new salt        bcrypt.hash(user.password, salt, function(err, hash) { if (err) return next(err); // override the cleartext password with the hashed one user.password = hash; next();        });    });});UserSchema.methods.comparePassword = function(candidatePassword, cb) {    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {        if (err) return cb(err);        cb(null, isMatch);    });};module.exports = mongoose.model('User', UserSchema);

用法

var mongoose = require(mongoose),    User = require('./user-model');var connStr = 'mongodb://localhost:27017/mongoose-bcrypt-test';mongoose.connect(connStr, function(err) {    if (err) throw err;    console.log('Successfully connected to MongoDB');});// create a user a new uservar testUser = new User({    username: 'jmar777',    password: 'Password123';});// save user to databasetestUser.save(function(err) {    if (err) throw err;});// fetch user and test password verificationUser.findOne({ username: 'jmar777' }, function(err, user) {    if (err) throw err;    // test a matching password    user.comparePassword('Password123', function(err, isMatch) {        if (err) throw err;        console.log('Password123:', isMatch); // -> Password123: true    });    // test a failing password    user.comparePassword('123Password', function(err, isMatch) {        if (err) throw err;        console.log('123Password:', isMatch); // -> 123Password: false    });});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/418946.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号