Skip to content

Commit 1439504

Browse files
Implement a method to password encrypt
1 parent 95fd61b commit 1439504

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/models/User.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { model, Schema, Document } from 'mongoose'
2+
import bcrypt from 'bcrypt'
23

34
export interface IUser extends Document {
45
displayName: string;
@@ -50,4 +51,14 @@ const UserSchema = new Schema({
5051
timestamps: true
5152
})
5253

54+
UserSchema.pre<IUser>('save', async function(next){
55+
const user = this
56+
if (!user.isModified('password')) return next()
57+
58+
const salt = await bcrypt.genSalt(10)
59+
const hash = await bcrypt.hash(user.password, salt)
60+
user.password = hash
61+
next()
62+
})
63+
5364
export default model<IUser>('User', UserSchema)

0 commit comments

Comments
 (0)