Created
March 2, 2024 13:06
-
-
Save hariscs/b7baf54ebd0897ccbce06bdaf930a75f to your computer and use it in GitHub Desktop.
Hash and Match Password in a Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import mongoose, { Document, Schema } from 'mongoose' | |
| import bcrypt from 'bcrypt' | |
| interface IUserSchema extends Document { | |
| name?: string | |
| email: string | |
| password: string | |
| match_password: (password: string) => Promise<boolean> | |
| } | |
| const user_schema = new Schema( | |
| { | |
| name: { type: String }, | |
| email: { type: String, required: true, unique: true }, | |
| password: { type: String, required: true }, | |
| }, | |
| { | |
| timestamps: true, | |
| } | |
| ) | |
| user_schema.pre('save', async function (next) { | |
| const user = this | |
| if (!user.isModified('password')) { | |
| next() | |
| return | |
| } | |
| const salt = await bcrypt.genSalt(10) | |
| this.password = await bcrypt.hash(this.password, salt) | |
| next() | |
| }) | |
| user_schema.methods.match_password = async function (entered_password: string) { | |
| return await bcrypt.compare(entered_password, this.password) | |
| } | |
| export const USER_SCHEMA = mongoose.model<IUserSchema>('User', user_schema) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment