42 lines
1.2 KiB
JavaScript
42 lines
1.2 KiB
JavaScript
import mongoose from 'mongoose';
|
|
import bcrypt from 'bcrypt';
|
|
require('dotenv').config();
|
|
|
|
const { SALT_WORK_FACTOR } = process.env;
|
|
|
|
const { Schema } = mongoose;
|
|
const UserSchema = new Schema({
|
|
username: { type: String, required: true, index: { unique: true } },
|
|
password: { type: String, required: true }
|
|
});
|
|
|
|
|
|
UserSchema.pre('save', next => {
|
|
var user = this;
|
|
// only hash the password if it has been modified (or is new)
|
|
if (!user.isModified('password')) return next();
|
|
|
|
// generate a salt
|
|
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
|
|
if (err) return next(err);
|
|
|
|
// hash the password along with our new salt
|
|
bcrypt.hash(user.password, salt, function(err, hash) {
|
|
if (err) return next(err);
|
|
|
|
// override the cleartext password with the hashed one
|
|
user.password = hash;
|
|
next();
|
|
});
|
|
});
|
|
});
|
|
|
|
UserSchema.methods.comparePassword = (candidatePassword, cb) => {
|
|
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
|
|
if (err) return cb(err);
|
|
cb(null, isMatch);
|
|
});
|
|
};
|
|
|
|
export default mongoose.model('User', UserSchema);
|