隐藏所有MongoDB查询的密码

时间:2016-07-04 11:45:31

标签: node.js mongodb mongoose

我有以下架构。它的用户和文档有几个字段。我需要的是,一旦用户注册密码变得隐藏,那么我运行密码的任何数据库查询(例如查找,更新等)始终都是隐藏的。

我知道排除/制作密码:mongo查询中的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},每当我做任何查询时,都不会返回密码。

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
      })
    }
  }
});

1 个答案:

答案 0 :(得分:2)

添加:

select: false

到用户模型中的密码属性。

password: {type: String,default: null,select:false}

顺便说一下,在将密码保存到数据库之前,您应该加密密码!