import bcrypt from 'bcrypt-nodejs' ; import mongoose from 'mongoose' ; import { NextFunction } from 'express' ; const PASSWORD_SALT_ROUND = 10 ; export interface UserModel extends mongoose . Document { username : string ; email : string ; password : string ; isAdmin : boolean ; updatedAt : Date ; } const userSchema = new mongoose . Schema ( { username : { type : String , unique : true } , email : { type : String , unique : true } , password : String , isAdmin : Boolean } , { timestamps : true } ) ; userSchema . index ( { username : 1 } , { unique : true } ) ; const hashPassword = ( password , callback ) => { bcrypt . genSalt ( PASSWORD_SALT_ROUND , ( err , salt ) => { if ( err ) { return callback ( err , '' ) ; } bcrypt . hash ( password , salt , undefined , ( mongooseErr , hash ) => { if ( mongooseErr ) { return callback ( mongooseErr , '' ) ; } callback ( null , hash ) ; } ) ; } ) ; } ; userSchema . pre ( 'save' , function ( next ) { const user = this as UserModel ; hashPassword ( user . password , ( err , hash ) => { if ( err ) { return next ( err ) ; } user . password = hash ; next ( ) ; } ) ; } ) ; const User = mongoose . model < UserModel > ( 'User' , userSchema ) ; export default User ;