Node.js 对所有MongoDB查询隐藏密码
我有以下模式。它包含一个用户,文档有几个字段。我需要的是,一旦用户注册,密码就会被隐藏,无论我运行哪个db查询(例如查找、更新等),密码都会保持隐藏 我知道mongo查询中的排除/生成密码:0,例如,截至目前,我使用以下方法排除密码:Node.js 对所有MongoDB查询隐藏密码,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有以下模式。它包含一个用户,文档有几个字段。我需要的是,一旦用户注册,密码就会被隐藏,无论我运行哪个db查询(例如查找、更新等),密码都会保持隐藏 我知道mongo查询中的排除/生成密码:0,例如,截至目前,我使用以下方法排除密码: User.find({} , {password: 0}).populate('favoriteListings').populate('myListings').populate('profilePicture').limit(size).skip(itemsT
User.find({} , {password: 0}).populate('favoriteListings').populate('myListings').populate('profilePicture').limit(size).skip(itemsToSkip)
.exec(function (err, result) { // LIMIT THE RESULT TO 5 DOCUMENTS PER QUERY
if (err) return next(err)
return res.json(result)
})
i、 e我在所有查询中都会从json结果中单独排除密码。我需要做的是像password:{hidden:true}这样的东西,并且每当我执行任何查询时,都不会返回密码
var mongoose = require('mongoose');
var Schema = mongoose.Schema; // creating schema
var Listing = require('../listing/listingModel');
var Media = require('../media/mediaModel');
var UserSchema = new Schema({
email: {type: String,default: null}, // EMAIL ID AND PASSWORD ARE TO BE KEPT ON MAIN OF SCHEMA
password: {type: String,default: null},
personal: { // personal information
firstName: {type: String,default: null},
lastName: {type: String,default: null},
dateOfBirth: { type: Date, default: Date.now },
description: {type: String,default: null},
contactNo: {type: String,default: '0000-0000-0000'},
gender: {
male: {type: Boolean,default: true},
female: {type: Boolean,default: false}
}
},
preferences: {
budget: {type: Number,default: 0},
moveInDate: { type: Date, default: Date.now },
profileViewable: {type: Boolean,default: true}
},
background: { // Has an array of work experiences
workExperience: [{ // can have multiple experiences so it is an array
employer: {type: String,default: null},
position: {type: String,default: null},
descrpiton: {type: String,default: null},
startDate: {type: Date,default: Date.now},
endDate: {type: Date,default: Date.now}
}]
},
profilePicture: { type: Schema.Types.ObjectId, ref: 'Media' },
favoriteListings: [{ type: Schema.Types.ObjectId, ref: 'Listing' }],
myListings: [{ type: Schema.Types.ObjectId, ref: 'Listing' }],
status: {type: Boolean,default: true} // STATUS OF ENTRY, BY DEFAULT ACTIVE=TRUE
},
{
// MAKING VIRTUALS TRUE
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
},
timestamps: true, // FOR createdAt and updatedAt
versionKey: false,
id: false // because toObject virtuals true creates another id field in addition to _id so making it false
}
)
UserSchema
.virtual('fullName')
.get(function () {
// console.log(this.createdAt)
if (this.firstName != null && this.lastName != null) {return this.name.firstName + ' ' + this.name.lastName}
else
return null
})
var User = mongoose.model('User', UserSchema)
module.exports = User
以下是登录用户的代码
User.findOne({
email: req.body.email
}).select('+hash +salt').exec( function (err, validadmin) {
if (err) return next(err)
if (!validadmin) {
res.json({ success: false, message: 'Authentication failed. User not found.' })
} else if (validadmin) {
var decryptedPassword = CryptoJS.AES.decrypt(validadmin.password, myPasswordKey) // DECRYPTING PASSWORD
// OBTAINED FROM DB TO MATCH WITH PASSWORD GIVEN BY USER
decryptedPassword = decryptedPassword.toString(CryptoJS.enc.Utf8)
console.log(decryptedPassword)
console.log(req.body.password)
// check if password matches
if (decryptedPassword != req.body.password) {
return res.json({ success: false, message: 'Authentication failed. Wrong password.' })
} else {
// CREATES TOKEN UPON SUCCESSFUL LOGIN
var token = jwt.sign(validadmin, app.get('superSecret'), {
expiresIn: 24 * 60 * 60
})
// LOGIN SUCCESSFUL
return res.json({
success: true,
message: 'LOGIN SUCCESSFUL!',
token: token
})
}
}
});
加:
到用户模型中的password属性
password: {type: String,default: null,select:false}
顺便说一句,您应该在将密码保存到数据库之前对其进行加密 在这种情况下,密码将从查询结果中隐藏。但当我使用密码和电子邮件登录时,下面的错误是TypeError:无法读取未定义的属性“salt”。顺便说一句,我正在使用jwt进行密码加密。在您的登录策略中,您必须检索数据库的用户,并对照尝试登录的用户进行检查,对吗?在搜索用户的查询中,添加。在find方法之后选择('+hash+salt')。例如,在查询数据库以显示用户配置文件时,如果您不想获取hash和salt,您还可以执行以下操作
user.find(id)…select('-hash-salt')
我认为这将有效地选择(-hash-salt)仍然没有用,相同的旧错误从模型中删除select:false属性,并在所有要查询用户信息的路由中使用.select('-hash-salt')
password: {type: String,default: null,select:false}