1
\$\begingroup\$

I have an Express router that is doing all the heavy lifting. Should the router be handling all this stuff or is a layer required between these two like maybe a service that makes these calls?

// Modules
import { Router } from 'express'
import Passport from 'passport'
import Sequelize from 'sequelize'
import _ from 'lodash'
import JWT from 'jsonwebtoken'
import process from 'process'

import User from '../models/User'
import JwtAuth from '../../config/authStrategy'

const router = new Router()

router.use(Passport.initialize())
JwtAuth(Passport)

router.post('/api/register', (req, res) => {
    User.create(req.body)
        .then(user =>
            res.status(201).json({
                success: true,
                message: `User ${user.name} with id ${
                    user.email
                } successfully created. Please login to continue.`
            })
        )
        .catch(Sequelize.UniqueConstraintError, err => {
            res.status(409).json({
                success: false,
                message: `User with id ${err.fields.email} already exists!`
            })
        })
        .catch(Sequelize.ValidationError, err => {
            const fields = _.capitalize(
                err.errors.map(error => error.path).join(', ')
            )
            res.status(400).json({
                success: false,
                message: `${fields} was not filled correctly. Please retry regestering.`
            })
        })
})

router.post('/api/login', (req, res) => {
    User.findOne({ where: { email: req.body.email } })
        .then(user => {
            if (user === null) {
                unsuccessfulLogin(res)
                return
            }
            user.comparePassword(req.body.password).then(isCorrect => {
                if (isCorrect) {
                    let token = JWT.sign(
                        user.dataValues,
                        process.env.JWT_SECRET,
                        { expiresIn: 10000 }
                    )
                    res.cookie('token', token)
                    res.status(303).json({
                        success: true,
                        message: 'Login successful',
                        token: `JWT ${token}`
                    })
                } else {
                    unsuccessfulLogin(res)
                }
            })
        })
        .catch(err => {
            console.error(err)
            unsuccessfulLogin(res)
        })
})

router.post(
    '/api/logout',
    Passport.authenticate('jwt', { session: false }),
    (req, res) => {
        req.logout()
        res.cookie('token', '')
        res.json({
            success: true,
            message: 'Successfully logged out'
        })
    }
)

function unsuccessfulLogin(res) {
    res.status(401).json({
        success: false,
        message: 'Login failed!'
    })
}

export default router
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.