generated from AdoryVo/node-website-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathUser.js
73 lines (67 loc) · 1.9 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
const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const sharp = require('sharp');
const validator = require('validator');
const userSchema = new mongoose.Schema({
firstName: {
type: String,
required: true,
trim: true
},
lastName: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
lowercase: true,
trim: true,
unique: true,
validate: {
validator: function (value) {
return validator.isEmail(value);
},
message: props => `${props.value} is not a valid email!`
}
},
password: {
type: String,
required: true
},
plan: {
type: String,
enum: {
values: ['Free', 'Premium', 'Admin'],
message: '{VALUE} is not supported'
},
default: 'Free'
},
posts: {
type: [mongoose.Schema.Types.ObjectId],
default: []
},
profile: {
type: {photo: Buffer}
// default: {photo: [declared below in 'save' hook]}
}
}, {collection: 'users', timestamps: true});
/* ---------- HOOKS ---------- */
/* ----- Pre ----- */
userSchema.pre('save', async function (next) {
// Condition will hold true when new user is created or password modification
if (this.isModified('password')) {
this.password = await bcrypt.hash(this.password, 10);
}
if (!this.isModified('profile.photo')) {
this.profile = {photo: await sharp('public/assets/profile-photo.png').resize(400, 400).toBuffer()};
}
next();
});
/* ---------- FUNCTIONS ---------- */
/* ----- Instance Methods ----- */
userSchema.methods.verifyPassword = function (inputPassword, callback) {
return bcrypt.compare(inputPassword, this.password, callback);
};
module.exports = mongoose.model('User', userSchema);