Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { check, validationResult, body } = require('express-validator/check')
- const sgMail = require('@sendgrid/mail')
- const bcrypt = require('bcrypt')
- const config = require('config')
- const { User, Role } = require('../../../models')
- const { checkToken, generateToken, handleJwtError } = require('./helpers')
- sgMail.setApiKey(config.get('email.sendGrid.apiKey'))
- exports.register = [
- body('email').exists().isEmail(),
- body('password').exists().isString().isLength({ min: 8 }),
- body('role').exists(),
- body('website').optional({ checkFalsy: true }).isURL(),
- body('title').optional({ checkFalsy: true }).isIn(['Mr', 'Mrs']),
- async (req, res, next) => {
- try {
- const errors = validationResult(req)
- if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
- const token = await generateToken({ email: req.body.email })
- const role = await Role.findOne({ where: { title: req.body.role }, row: true })
- await User.create(
- { ...req.body, roleId: role.id, confirmed: process.env.NODE_ENV === 'development' },
- { fields: [
- 'email',
- 'firstName',
- 'middleName',
- 'lastName',
- 'title',
- 'image',
- 'password',
- 'roleId',
- 'confirmed',
- 'ssn',
- 'phone',
- 'countryCode',
- 'city',
- 'website'
- ]}
- )
- await sgMail.send({
- from: config.get('email.from'),
- to: req.body.email,
- subject: 'Confirm your email on hire-match',
- // eslint-disable-next-line max-len
- html: `To confirm your email please follow the <a href="${config.get('email.url')}/confirm-email/${token}">link</a>`
- })
- res.sendStatus(200)
- } catch (err) {
- if (err.name === 'SequelizeUniqueConstraintError') {
- res.status(400).json({ message: 'This email is already taken' })
- return
- }
- next(err)
- }
- }
- ]
- exports.confirmEmail = [
- check('token').exists().isString(),
- async (req, res, next) => {
- try {
- const errors = validationResult(req)
- if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
- const { email } = await checkToken(req.body.token)
- await User.update({ confirmed: true }, { where: { email } })
- res.sendStatus(200)
- } catch (err) {
- if (err.name && err.name.includes('Token')) return handleJwtError(err, res)
- next(err)
- }
- }
- ]
- exports.login = [
- body('email').exists().isEmail(),
- body('password').exists(),
- async (req, res, next) => {
- try {
- const errors = validationResult(req)
- if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
- const user = await User.findOne({
- where: { email: req.body.email },
- include: [{
- model: Role,
- as: 'role'
- }]
- })
- if (!user) return res.status(404).json({ message: 'Unable to find user' })
- if (!user.confirmed) return res.status(401).json({ message: 'You need to confirm user' })
- const validPassword = await bcrypt.compare(req.body.password, user.password)
- if (!validPassword) return res.status(401).json({ message: 'Wrong password' })
- const token = await generateToken({ id: user.id, email: req.body.email, role: user.role.title })
- res.json({ token })
- } catch (err) {
- next(err)
- }
- }
- ]
- exports.initiateForgotPassword = [
- body('email').exists().isEmail(),
- async (req, res, next) => {
- try {
- const errors = validationResult(req)
- if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
- const token = await generateToken({ email: req.body.email }, '20m')
- const [result] = await User.update({ resetPasswordToken: token }, { where: { email: req.body.email } })
- if (!result) return res.status(404).json({ message: 'Unable to find user' })
- sgMail.send({
- from: config.get('email.from'),
- to: req.body.email,
- subject: 'Change password',
- text: `Your token ${token}`
- })
- res.sendStatus(200)
- } catch (err) {
- next(err)
- }
- }
- ]
- exports.passwordReset = [
- body('token').exists(),
- body('password').exists(),
- async (req, res, next) => {
- try {
- const errors = validationResult(req)
- if (!errors.isEmpty()) return res.status(400).json({ errors: errors.mapped() })
- const { email } = await checkToken(req.body.token)
- const password = await bcrypt.hash(req.body.password, 10)
- const [result] = await User.update(
- { password, resetPasswordToken: null },
- { where: { email, resetPasswordToken: req.body.token } }
- )
- if (!result) return res.status(400).json({ message: 'Unable to reset password' })
- res.sendStatus(200)
- } catch (err) {
- if (err.name && err.name.includes('Token')) return handleJwtError(err, res)
- next(err)
- }
- }
- ]
Add Comment
Please, Sign In to add comment