Skip to content

Instantly share code, notes, and snippets.

@teerasej
Last active December 22, 2021 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teerasej/3acc2eec90b5a5aad4f7134a818207c3 to your computer and use it in GitHub Desktop.
Save teerasej/3acc2eec90b5a5aad4f7134a818207c3 to your computer and use it in GitHub Desktop.
// 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