2014-03-31 11:46:28 -04:00
sanitize = require ( ' sanitizer ' )
2014-04-10 09:43:06 -04:00
User = require ( " ../../models/User " ) . User
UserCreator = require ( " ./UserCreator " )
AuthenticationManager = require ( " ../Authentication/AuthenticationManager " )
2014-04-10 17:21:20 -04:00
NewsLetterManager = require ( " ../Newsletter/NewsletterManager " )
2014-04-10 09:43:06 -04:00
async = require ( " async " )
EmailHandler = require ( " ../Email/EmailHandler " )
logger = require ( " logger-sharelatex " )
2014-02-12 05:23:40 -05:00
module.exports =
validateEmail : (email) ->
re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re . test ( email )
hasZeroLengths : (props) ->
hasZeroLength = false
props . forEach (prop) ->
if prop . length == 0
hasZeroLength = true
return hasZeroLength
2014-04-10 09:43:06 -04:00
_registrationRequestIsValid : (body, callback)->
email = sanitize . escape ( body . email ) . trim ( ) . toLowerCase ( )
password = body . password
2014-02-12 05:23:40 -05:00
username = email . match ( /^[^@]*/ )
if @ hasZeroLengths ( [ password , email ] )
2014-04-10 09:43:06 -04:00
return false
2014-02-12 05:23:40 -05:00
else if ! @ validateEmail ( email )
2014-04-10 09:43:06 -04:00
return false
2014-02-12 05:23:40 -05:00
else
2014-04-10 09:43:06 -04:00
return true
2014-04-10 07:39:13 -04:00
2014-04-10 09:43:06 -04:00
_createNewUserIfRequired: (user, userDetails, callback)->
if ! user ?
UserCreator . createNewUser { holdingAccount : false , email : userDetails . email } , callback
else
callback null , user
2014-04-10 07:39:13 -04:00
registerNewUser: (userDetails, callback)->
2014-04-10 09:43:06 -04:00
self = @
requestIsValid = @ _registrationRequestIsValid userDetails
if ! requestIsValid
return callback ( " request is not valid " )
userDetails.email = userDetails . email ? . trim ( ) ? . toLowerCase ( )
User . findOne email : userDetails . email , (err, user)->
if err ?
return callback err
if user ? . holdingAccount == false
return callback ( " EmailAlreadyRegisterd " )
self . _createNewUserIfRequired user , userDetails , (err, user)->
if err ?
return callback ( err )
async . series [
(cb)-> User . update { _id: user . _id } , { " $set " : { holdingAccount : false } } , cb
(cb)-> AuthenticationManager . setUserPassword user . _id , userDetails . password , cb
(cb)-> NewsLetterManager . subscribe user , cb
(cb)->
emailOpts =
first_name : user . first_name
to: user . email
EmailHandler . sendEmail " welcome " , emailOpts , cb
] , (err)->
logger . log user: user , " registered "
callback ( err , user )
2014-04-10 07:39:13 -04:00