My colleague's code that I need to integrate into my website is structured in a class and asynchronous style for the database. While I personally don't see the necessity for this approach, I have found that it is not harmful:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
class User {
constructor() {
this.user = mongoose.model('user', {
email: String,
password: String,
hash: String,
salt: String,
})
}
checkEmailPassword(email, password) {
return new Promise((resolve, reject) => {
this.user.find({email, password}, {}, (err, users) => {
if(err) throw(err)
if(users.length > 0) resolve(users[0])
else reject('not found')
})
})
}
addAccountWOCheck(userInf, way) {
return new Promise((resolve, reject) => {
var collection = new this.user(userInf)
// collection.setPassword(userInf.password)
collection.save((err, data) => {
if (err) throw (err)
else resolve(data)
})
})
}
}
My next challenge is to create a setPassword
function that will encrypt the user's password. I want this function to be called by a user instance rather than the class itself, but I'm unsure of how to implement this within the existing class:
setPassword = function(email) {
var salt = crypto.randomBytes(16).toString('hex');
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'SHA1').toString('hex');
}
If anyone has any insights or guidance on this matter, I would greatly appreciate it.
Edit 1:
I made an attempt to include the setPassword
function within the class:
setPassword(collection) {
collection.hash = "abc";
console.log("setPassword: " + JSON.stringify(collection));
}
and then called it within the addAccountWOCheck
method:
var collection = new this.user(userInf)
this.setPassword(collection)
collection.save((err, data) => {
if (err) throw (err)
else resolve(data)
})
While I can see that setPassword
is being called, the collection
is not being modified in the database as expected.