@@ -43,6 +43,16 @@ export async function createUser(req, res) {
43
43
try {
44
44
const { username, email, password } = req . body ;
45
45
const emailLowerCase = email . toLowerCase ( ) ;
46
+ const existingUser = await User . findByEmailAndUsername ( email , username ) ;
47
+ if ( existingUser ) {
48
+ const fieldInUse =
49
+ existingUser . email . toLowerCase ( ) === emailLowerCase
50
+ ? 'Email'
51
+ : 'Username' ;
52
+ res . status ( 422 ) . send ( { error : `${ fieldInUse } is in use` } ) ;
53
+ return ;
54
+ }
55
+
46
56
const EMAIL_VERIFY_TOKEN_EXPIRY_TIME = Date . now ( ) + 3600000 * 24 ; // 24 hours
47
57
const token = await generateToken ( ) ;
48
58
const user = new User ( {
@@ -53,34 +63,35 @@ export async function createUser(req, res) {
53
63
verifiedToken : token ,
54
64
verifiedTokenExpires : EMAIL_VERIFY_TOKEN_EXPIRY_TIME
55
65
} ) ;
56
- const existingUser = await User . findByEmailAndUsername ( email , username ) ;
57
- if ( existingUser ) {
58
- const fieldInUse =
59
- existingUser . email . toLowerCase ( ) === emailLowerCase
60
- ? 'Email'
61
- : 'Username' ;
62
- res . status ( 422 ) . send ( { error : `${ fieldInUse } is in use` } ) ;
63
- return ;
64
- }
66
+
65
67
await user . save ( ) ;
66
- req . logIn ( user , ( loginErr ) => {
68
+
69
+ req . logIn ( user , async ( loginErr ) => {
67
70
if ( loginErr ) {
68
- throw loginErr ;
71
+ console . error ( loginErr ) ;
72
+ res . status ( 500 ) . json ( { error : 'Failed to log in user.' } ) ;
73
+ return ;
69
74
}
70
- } ) ;
71
75
72
- const protocol = process . env . NODE_ENV === 'production' ? 'https' : 'http' ;
73
- const mailOptions = renderEmailConfirmation ( {
74
- body : {
75
- domain : `${ protocol } ://${ req . headers . host } ` ,
76
- link : `${ protocol } ://${ req . headers . host } /verify?t=${ token } `
77
- } ,
78
- to : req . user . email
79
- } ) ;
76
+ const protocol = process . env . NODE_ENV === 'production' ? 'https' : 'http' ;
77
+ const mailOptions = renderEmailConfirmation ( {
78
+ body : {
79
+ domain : `${ protocol } ://${ req . headers . host } ` ,
80
+ link : `${ protocol } ://${ req . headers . host } /verify?t=${ token } `
81
+ } ,
82
+ to : req . user . email
83
+ } ) ;
80
84
81
- await mail . send ( mailOptions ) ;
82
- res . json ( userResponse ( req . user ) ) ;
85
+ try {
86
+ await mail . send ( mailOptions ) ;
87
+ res . json ( userResponse ( user ) ) ;
88
+ } catch ( mailErr ) {
89
+ console . error ( mailErr ) ;
90
+ res . status ( 500 ) . json ( { error : 'Failed to send verification email.' } ) ;
91
+ }
92
+ } ) ;
83
93
} catch ( err ) {
94
+ console . error ( err ) ;
84
95
res . status ( 500 ) . json ( { error : err } ) ;
85
96
}
86
97
}
0 commit comments