Created
November 8, 2021 13:29
-
-
Save OmkarK45/71e93d662458f15a098361b811195eea to your computer and use it in GitHub Desktop.
Auth handler that handles new signups on the platform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const signUpHandler: RequestHandler<{}, {}, SignUpBody> = async ( | |
req, | |
res | |
) => { | |
const { firstName, lastName, email, password } = req.body | |
const isAlreadyRegistered = await User.findOne({ | |
email, | |
}) | |
if (isAlreadyRegistered) { | |
return res.status(409).json({ | |
msg: 'An account with that email already exists. Please log in instead.', | |
}) | |
} | |
try { | |
const user = new User({ | |
firstName, | |
lastName, | |
email, | |
password, | |
}) | |
const verificationToken = await user.getEmailVerificationToken() | |
const verificationLink = `${req.get( | |
'origin' | |
)}/auth/email-verification/${verificationToken}` | |
await user.save((err) => { | |
if (err) { | |
return res.status(500).json({ | |
msg: 'Something went wrong while registering you. Please try later or contact [email protected]', | |
}) | |
} | |
}) | |
try { | |
await new Email({ | |
email: user.email, | |
firstName: user.firstName, | |
}).send({ | |
subject: '[neoG Camp] Please verify your email address.', | |
template: 'verify-email', | |
variables: { | |
verificationLink: verificationLink, | |
}, | |
}) | |
return res.status(200).json({ | |
msg: `An email with verification link has been sent to you at ${user.email}. Please check your inbox.`, | |
user: { | |
email: user.email, | |
firstName: user.firstName, | |
lastName: user.lastName, | |
_id: user._id, | |
}, | |
}) | |
} catch (error) { | |
user.verificationToken = undefined | |
user.verificationTokenExpiresIn = undefined | |
user.isVerified = false | |
user.save() | |
res.status(500).json({ | |
msg: 'There was an error while sending verification email. Please click the resend button.', | |
}) | |
} | |
} catch (error) { | |
res.status(500).json({ | |
msg: 'Something went wrong while registering you.', | |
code: 'INTERNAL_ERROR', | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment