Last active
April 14, 2024 03:38
-
-
Save jgololicic/224cf75b89039be4162ff6439fe0e7d8 to your computer and use it in GitHub Desktop.
Mongoose, Typescript, Pre hook, hash password, compare passwords
This file contains 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 * as mongoose from 'mongoose'; | |
import {Schema} from 'mongoose'; | |
const bcrypt = require('bcrypt-nodejs'); | |
const userSchema = new Schema({ | |
local: { | |
username: String, | |
email: {type: String, unique: true, index: true, sparse: true, lowercase: true, trim: true}, | |
password: String, | |
emailVerified: {type: Boolean, default: false} | |
}, | |
google: { | |
id: {type: String, unique: true, index: true, sparse: true}, | |
token: String, | |
email: {type: String, unique: true}, | |
name: String | |
} | |
}); | |
userSchema.pre('save', function (next) { | |
if (this.isModified('local.password')) { | |
bcrypt.genSalt(10, (err, salt) => { | |
if (err) { | |
return next(err); | |
} | |
bcrypt.hash(this.local.password, | |
salt, null, (error, hash) => { | |
if (error) { | |
return next(error); | |
} | |
this.local.password = hash; | |
return next(null, this); | |
}); | |
}); | |
} | |
return next(null, this); | |
}); | |
userSchema.methods.comparePasswords = (candidatePassword, next) => { | |
bcrypt.compare(candidatePassword, this.local.password, function (err, isMatch) { | |
if (err) { | |
return next(err); | |
} | |
next(null, isMatch); | |
}); | |
}; | |
userSchema.methods.generateHash = function (password) { | |
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); | |
}; | |
userSchema.methods.isPasswordValid = function (password) { | |
return bcrypt.compareSync(password, this.local.password); | |
}; | |
// Omit the password when returning a user | |
userSchema.set('toJSON', { | |
transform: function (doc, ret) { | |
delete ret.local.password; | |
return ret; | |
} | |
}); | |
export const User = mongoose.model('User', userSchema); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment