0
다음 스키마가 있습니다. 그것의 사용자와 문서의 여러 필드가 있습니다. 내가 필요로하는 것은 일단 사용자가 비밀 번호에 가입하면 비밀 번호를 항상 실행하는 db 쿼리 (예 : 찾기, 업데이트 등)가 항상 숨겨져 있다는 것입니다.모든 MongoDB 쿼리에서 비밀번호 숨기기
나는 제외/암호 만들기에 대해 알고 있습니다 : 0 문둥어 검색어, 예 : 현재로서는 나는 다음과 같은 방법을 사용하여 암호를 제외하고 :
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)
})
즉 내가 모든 쿼리에 개별적으로 JSON 결과에서 암호를 제외하고있다. 내가 필요한 것은 암호와 같은 것을 만드는 것입니다 : {hidden : true} 그리고 언제든지 쿼리 암호가 반환되지 않습니다. 귀하의 사용자 모델에서 암호 속성
select: false
: 다음
는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
})
}
}
});
이 경우 비밀번호는 쿼리 결과에서 숨겨집니다. 하지만 암호를 사용하여 로그인 할 때 다음 오류가 발생하면 TypeError : 정의되지 않은 "salt"속성을 읽을 수 없습니다. Btw 나는 암호 암호화를 위해 jwt를 사용하고 있습니다. – SyedAliRazaSherazi
로그인 전략에서 데이터베이스에 대한 사용자를 검색하고 로그인을 시도하는 사용자와 대조해야합니까? 사용자를 검색하는 쿼리에서 find 메서드 뒤에 .select ('+ hash + salt')를 추가합니다. –
사용자 프로필을 표시하기 위해 데이터베이스를 쿼리 할 때 해시 및 솔트를 가져 오지 않으려면 다음을 수행하십시오. 'User.find (id) .. select ('- hash - 소금 ')' 나는 –