-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.js
53 lines (48 loc) · 1.4 KB
/
users.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var mongoose = require('mongoose');
var crypto = require('crypto');
var userSchema = new mongoose.Schema({
email: {type: String, required: true, unique:true, lowercase:true},
phone: {type: Number},
city: {type: String},
salt: String,
hash: String
});
userSchema.pre('save', function(next) {
var password = this.salt;
this.salt = crypto.randomBytes(16).toString('hex');
console.log("password:" + password);
console.log(this);
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
console.log(this.salt + " and this.hash: " + this.hash);
next();
});
userSchema.methods.comparePasswords = function(password) {
console.log("inside commparePasswords: " + password);
console.log(this);
var salt = this.salt;
hash = crypto.pbkdf2Sync(password, salt, 1000, 64).toString('hex');
return hash === this.hash;
};
userSchema.statics.findByEmailPassword = function(user, done) {
this.findOne({email: user.email}, function(err, result){
if(err) {
console.log(err);
done(err);
};
if(!result) {
console.log("empty result meaning user doesn't exist");
done(null, false, " No user exists");
}
else
{
if(result.comparePasswords(user.password)) {
console.log("user exists.. proper creds");
done(null, result);
} else {
console.log("incorrect password");
done(null, false, "Incorrect Password");
}
}
})
}
module.exports = mongoose.model("User", userSchema);