Guest User

Untitled

a guest
Jun 20th, 2018
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.85 KB | None | 0 0
  1. const { check, validationResult, body } = require('express-validator/check')
  2. const sgMail = require('@sendgrid/mail')
  3. const bcrypt = require('bcrypt')
  4. const config = require('config')
  5.  
  6. const { User, Role } = require('../../../models')
  7. const { checkToken, generateToken, handleJwtError } = require('./helpers')
  8.  
  9. sgMail.setApiKey(config.get('email.sendGrid.apiKey'))
  10.  
  11. exports.register = [
  12. body('email').exists().isEmail(),
  13. body('password').exists().isString().isLength({ min: 8 }),
  14. body('role').exists(),
  15. body('website').optional({ checkFalsy: true }).isURL(),
  16. body('title').optional({ checkFalsy: true }).isIn(['Mr', 'Mrs']),
  17.  
  18. async (req, res, next) => {
  19. try {
  20. const errors = validationResult(req)
  21. if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
  22.  
  23. const token = await generateToken({ email: req.body.email })
  24. const role = await Role.findOne({ where: { title: req.body.role }, row: true })
  25.  
  26. await User.create(
  27. { ...req.body, roleId: role.id, confirmed: process.env.NODE_ENV === 'development' },
  28. { fields: [
  29. 'email',
  30. 'firstName',
  31. 'middleName',
  32. 'lastName',
  33. 'title',
  34. 'image',
  35. 'password',
  36. 'roleId',
  37. 'confirmed',
  38. 'ssn',
  39. 'phone',
  40. 'countryCode',
  41. 'city',
  42. 'website'
  43. ]}
  44. )
  45.  
  46. await sgMail.send({
  47. from: config.get('email.from'),
  48. to: req.body.email,
  49. subject: 'Confirm your email on hire-match',
  50. // eslint-disable-next-line max-len
  51. html: `To confirm your email please follow the <a href="${config.get('email.url')}/confirm-email/${token}">link</a>`
  52. })
  53.  
  54. res.sendStatus(200)
  55. } catch (err) {
  56. if (err.name === 'SequelizeUniqueConstraintError') {
  57. res.status(400).json({ message: 'This email is already taken' })
  58. return
  59. }
  60.  
  61. next(err)
  62. }
  63. }
  64. ]
  65.  
  66. exports.confirmEmail = [
  67. check('token').exists().isString(),
  68.  
  69. async (req, res, next) => {
  70. try {
  71. const errors = validationResult(req)
  72. if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
  73.  
  74. const { email } = await checkToken(req.body.token)
  75. await User.update({ confirmed: true }, { where: { email } })
  76.  
  77. res.sendStatus(200)
  78. } catch (err) {
  79. if (err.name && err.name.includes('Token')) return handleJwtError(err, res)
  80. next(err)
  81. }
  82. }
  83. ]
  84.  
  85. exports.login = [
  86. body('email').exists().isEmail(),
  87. body('password').exists(),
  88.  
  89. async (req, res, next) => {
  90. try {
  91. const errors = validationResult(req)
  92. if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
  93.  
  94. const user = await User.findOne({
  95. where: { email: req.body.email },
  96. include: [{
  97. model: Role,
  98. as: 'role'
  99. }]
  100. })
  101.  
  102. if (!user) return res.status(404).json({ message: 'Unable to find user' })
  103. if (!user.confirmed) return res.status(401).json({ message: 'You need to confirm user' })
  104.  
  105. const validPassword = await bcrypt.compare(req.body.password, user.password)
  106. if (!validPassword) return res.status(401).json({ message: 'Wrong password' })
  107.  
  108. const token = await generateToken({ id: user.id, email: req.body.email, role: user.role.title })
  109. res.json({ token })
  110. } catch (err) {
  111. next(err)
  112. }
  113. }
  114. ]
  115.  
  116. exports.initiateForgotPassword = [
  117. body('email').exists().isEmail(),
  118.  
  119. async (req, res, next) => {
  120. try {
  121. const errors = validationResult(req)
  122. if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
  123.  
  124. const token = await generateToken({ email: req.body.email }, '20m')
  125. const [result] = await User.update({ resetPasswordToken: token }, { where: { email: req.body.email } })
  126.  
  127. if (!result) return res.status(404).json({ message: 'Unable to find user' })
  128.  
  129. sgMail.send({
  130. from: config.get('email.from'),
  131. to: req.body.email,
  132. subject: 'Change password',
  133. text: `Your token ${token}`
  134. })
  135.  
  136. res.sendStatus(200)
  137. } catch (err) {
  138. next(err)
  139. }
  140. }
  141. ]
  142.  
  143. exports.passwordReset = [
  144. body('token').exists(),
  145. body('password').exists(),
  146.  
  147. async (req, res, next) => {
  148. try {
  149. const errors = validationResult(req)
  150. if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
  151.  
  152. const { email } = await checkToken(req.body.token)
  153. const password = await bcrypt.hash(req.body.password, 10)
  154.  
  155. const [result] = await User.update(
  156. { password, resetPasswordToken: null },
  157. { where: { email, resetPasswordToken: req.body.token } }
  158. )
  159.  
  160. if (!result) return res.status(400).json({ message: 'Unable to reset password' })
  161. res.sendStatus(200)
  162. } catch (err) {
  163. if (err.name && err.name.includes('Token')) return handleJwtError(err, res)
  164. next(err)
  165. }
  166. }
  167. ]
Add Comment
Please, Sign In to add comment