All files / src/routes signin.ts

89.47% Statements 17/19
0% Branches 0/2
100% Functions 2/2
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 304x 4x 4x 4x   4x   4x         4x 4x 2x 2x 2x 2x   2x         2x 2x     4x  
import express, { Request, Response } from 'express'
import jwt from 'jsonwebtoken'
import { body } from 'express-validator'
import { UnauthorizedError, validateRequest } from '@next-k8s/common'
 
import User, { UserDoc } from '../models/user'
 
const validateInput = [
  body('email').isEmail().withMessage('Email must be a valid email address'),
  body('password').trim().notEmpty().withMessage('A password must be provided')
]
 
const router = express.Router()
router.post('/api/users/signin', validateInput, validateRequest, async (req: Request, res: Response) => {
  const user = await User.findOne({ email: req.body.email }).exec()
  Iif (!user) throw new UnauthorizedError('Incorrect username or password', 401, req.body.email)
  const validPassword = await (user as UserDoc).verifyPassword(req.body.password)
  Iif (!validPassword) throw new UnauthorizedError('Incorrect username or password', 401, req.body.email)
 
  const token = jwt.sign({
    id: user.id,
    email: user.email
  }, process.env.JWT_KEY!)
 
  req.session = { jwt: token }
  res.json({ user, jwt: token })
})
 
export default router