Last active
December 22, 2021 08:04
-
-
Save teerasej/3acc2eec90b5a5aad4f7134a818207c3 to your computer and use it in GitHub Desktop.
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
// schemas/user.js | |
import mongoose from 'mongoose'; | |
import Joi from 'joi'; | |
import passwordComplexity from 'joi-password-complexity'; | |
import bcrypt from 'bcrypt'; | |
const SALT_ROUNDS = 12; | |
const emailValidator = Joi.string().email(); | |
const userSchema = new mongoose.Schema({ | |
email: { | |
type: String, | |
required: true, | |
trim: true, | |
validate: { | |
validator: function(value) { | |
const result = emailValidator.validate(value); | |
return result.error == undefined; | |
}, | |
message: function(props) { | |
return props.value + ' is not correct email format.'; | |
} | |
} | |
}, | |
password: { | |
type: String, | |
required: true, | |
trim: true, | |
minlength: 6, | |
validate: { | |
validator: function(value) { | |
const passwordValidator = passwordComplexity({ | |
min: 6, | |
max: 30, | |
lowerCase: 1, | |
upperCase: 1, | |
numeric: 1, | |
requirementCount: 4 | |
}); | |
const result = passwordValidator.validate(value); | |
return result.error == undefined; | |
}, | |
message: function(props) { | |
return 'your password need at least 1 Uppercase, 1 lowercase, 1 number'; | |
} | |
} | |
} | |
}); | |
userSchema.pre('save', async function preSave(next){ | |
const user = this; | |
if(!user.isModified('password')) return next(); | |
try { | |
console.log('user password: ' + user.password); | |
user.password = await bcrypt.hash(user.password, SALT_ROUNDS); | |
return next(); | |
} catch (error) { | |
return next(error); | |
} | |
}); | |
userSchema.methods.comparePassword | |
= async function comparePassword(candidate) { | |
return bcrypt.compare(candidate, this.password); | |
} | |
const UserModel = mongoose.model('User', userSchema); | |
export default UserModel; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment