11const mongoose = require ( 'mongoose' ) ;
22const bcrypt = require ( 'bcrypt' ) ;
33import isEmail from 'validator/lib/isEmail' ;
4+
45const Schema = mongoose . Schema ;
56
67const UserSchema = new mongoose . Schema ( {
@@ -11,7 +12,7 @@ const UserSchema = new mongoose.Schema({
1112 trim : true ,
1213 index : true
1314 } ,
14- fullName :{
15+ fullName : {
1516 type : String ,
1617 required : true ,
1718 trim : true
@@ -23,40 +24,52 @@ const UserSchema = new mongoose.Schema({
2324} ) ;
2425
2526// authenticate input against database documents
26- UserSchema . statics . authenticate = function ( email , password , callback ) {
27- User . findOne ( { emailAddress : email } )
27+ UserSchema . statics . authenticate = function ( email , password , callback ) {
28+ User . findOne ( { emailAddress : email } )
2829 . exec ( function ( error , user ) {
2930 if ( error ) {
3031 return callback ( error ) ;
31- } else if ( ! user ) {
32+ } else if ( ! user ) {
3233 let err = new Error ( 'User not found.' ) ;
3334 err . status = 401 ;
3435 return callback ( err ) ;
3536 }
36- bcrypt . compare ( password , user . password , function ( error , result ) {
37+ bcrypt . compare ( password , user . password , function ( error , result ) {
3738 if ( result === true ) {
3839 return callback ( null , user ) ;
3940 }
4041 return callback ( ) ;
41-
42- } )
42+ } ) ;
4343 } ) ;
4444} ;
4545
4646
47-
4847/*
4948May need some logic here later to check if email in correct format.
5049 */
51- UserSchema . statics . validEmail = function ( email ) {
50+ UserSchema . statics . validEmail = function ( email ) {
5251 email = email + '' ;
5352 return isEmail ( email ) ;
5453} ;
5554
55+ UserSchema . statics . userExist = function ( email , callback ) {
56+ User . findOne ( { emailAddress : email } )
57+ . exec ( function ( error , user ) {
58+ if ( error ) {
59+ return callback ( error ) ;
60+ } else if ( user ) {
61+ const err = new Error ( 'User Already Exists' ) ;
62+ err . status = 409 ;
63+ return callback ( err ) ;
64+ }
65+ return callback ( null ) ;
66+ } ) ;
67+ } ;
68+
5669
5770//hash password before saving to database
5871// hash password before saving to database
59- UserSchema . pre ( 'save' , function ( next ) { //This has to be function. for some reason. tried without and it fails..
72+ UserSchema . pre ( 'save' , function ( next ) { //This has to be function. for some reason. tried without and it fails..
6073 const user = this ;
6174 bcrypt . hash ( user . password , 10 , ( err , hash ) => {
6275 if ( err ) {
0 commit comments