-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUser.js
76 lines (68 loc) · 1.68 KB
/
User.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const bcrypt = require("bcrypt");
const crypto = require("crypto");
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema(
{
email: { type: String, unique: true },
password: String,
passwordResetToken: String,
passwordResetExpires: Date,
emailVerificationToken: String,
emailVerified: Boolean,
twitter: String,
google: String,
tokens: Array,
favoriteRecipes: Array,
userName: { type: String },
profile: {
name: String,
gender: String,
location: String,
website: String,
picture: String,
},
},
{ timestamps: true }
);
// Password hash middleware.
userSchema.pre("save", function save(next) {
const user = this;
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});
// Helper method for validating user's password.
userSchema.methods.comparePassword = function comparePassword(
candidatePassword,
cb
) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
};
/**
* Helper method for getting user's gravatar.
*/
userSchema.methods.gravatar = function gravatar(size) {
if (!size) {
size = 200;
}
if (!this.email) {
return `https://gravatar.com/avatar/?s=${size}&d=retro`;
}
const md5 = crypto.createHash("md5").update(this.email).digest("hex");
return `https://gravatar.com/avatar/${md5}?s=${size}&d=retro`;
};
module.exports = mongoose.model("User", userSchema, "User");