forked from TomDoesTech/Testing-Express-REST-API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.model.ts
More file actions
51 lines (39 loc) · 1.16 KB
/
Copy pathuser.model.ts
File metadata and controls
51 lines (39 loc) · 1.16 KB
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
import mongoose from "mongoose";
import bcrypt from "bcrypt";
import config from "config";
export interface UserDocument extends mongoose.Document {
email: string;
name: string;
password: string;
createdAt: Date;
updatedAt: Date;
comparePassword(candidatePassword: string): Promise<Boolean>;
}
const userSchema = new mongoose.Schema(
{
email: { type: String, required: true, unique: true },
name: { type: String, required: true },
password: { type: String, required: true },
},
{
timestamps: true,
}
);
userSchema.pre("save", async function (next) {
let user = this as UserDocument;
if (!user.isModified("password")) {
return next();
}
const salt = await bcrypt.genSalt(config.get<number>("saltWorkFactor"));
const hash = await bcrypt.hashSync(user.password, salt);
user.password = hash;
return next();
});
userSchema.methods.comparePassword = async function (
candidatePassword: string
): Promise<boolean> {
const user = this as UserDocument;
return bcrypt.compare(candidatePassword, user.password).catch((e) => false);
};
const UserModel = mongoose.model<UserDocument>("User", userSchema);
export default UserModel;