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);