forked from makeitrealcamp/node-auth-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
userSchema.js
44 lines (39 loc) · 946 Bytes
/
userSchema.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
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
required: true
}
}, { autoIndex: false });
// hashes the password
UserSchema.pre("save", function (next) {
bcrypt.hash(this.password, 10, (err, hash) => {
if (err) {
return next(err);
}
this.password = hash;
next();
});
});
// used for authentication
UserSchema.statics.authenticate = async (email, password) => {
const user = await mongoose.model("User").findOne({ email: email });
if (user) {
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, result) => {
if (err) reject(err);
resolve(result === true ? user : null);
});
});
return user;
}
return null;
};
module.exports = UserSchema;