All files / bc-mongodb-implementation-demo/src/features/users user.controller.js

85.71% Statements 30/35
81.25% Branches 13/16
66.66% Functions 2/3
85.71% Lines 30/35

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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 1112x 2x 2x 2x         2x         2x 3x 3x 1x     2x 2x 1x       1x   1x           1x   1x               1x                           2x 3x 3x 1x     2x 2x       2x 2x 1x     1x           1x                             2x                             2x  
const User = require('./user.model')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const { StatusCodes } = require('http-status-codes')
const {
  BadRequestError,
  UnauthenticatedError,
  NotFoundError,
} = require('../../errors')
 
// @desc Register a new user
// @route POST /api/users
// @access Public
const register = async (req, res) => {
  const { email, password } = req.body
  if (!email || !password) {
    throw new BadRequestError('Email and password are required')
  }
 
  const userAvailable = await User.findOne({ email })
  if (userAvailable) {
    throw new BadRequestError('User already exists')
  }
 
  // Hash the password
  const hashedPassword = await bcrypt.hash(password, 10)
 
  const newUser = new User({
    email,
    password: hashedPassword,
    role: 'customer', // Default role
  })
 
  await newUser.save()
 
  const token = jwt.sign(
    {
      user: { id: newUser._id, role: newUser.role },
    },
    process.env.JWT_SECRET_KEY,
    { expiresIn: '24h' },
  )
 
  res.status(StatusCodes.CREATED).json({
    message: 'User registered successfully',
    token,
    user: {
      id: newUser._id,
      email: newUser.email,
      role: newUser.role,
    },
  })
}
 
// @desc Login user
// @route POST /api/users/login
// @access Public
const login = async (req, res) => {
  const { email, password } = req.body
  if (!email || !password) {
    throw new BadRequestError('Email and password are required')
  }
 
  const user = await User.findOne({ email })
  Iif (!user) {
    throw new UnauthenticatedError('Invalid credentials')
  }
 
  const isPasswordValid = await bcrypt.compare(password, user.password)
  if (!isPasswordValid) {
    throw new UnauthenticatedError('Invalid credentials')
  }
 
  const token = jwt.sign(
    { user: { id: user._id, role: user.role, userName: user.userName } },
    process.env.JWT_SECRET_KEY,
    { expiresIn: '24h' },
  )
 
  res.status(StatusCodes.OK).json({
    message: 'Login successful',
    token,
    user: {
      id: user._id,
      email: user.email,
      userName: user.userName,
      role: user.role,
    },
  })
}
 
// @desc Get current user
// @route GET /api/users/current
// @access Private
const currentUser = async (req, res) => {
  const user = await User.findById(req.user.id).select('-password')
  if (!user) {
    throw new NotFoundError('User not found')
  }
  res.status(StatusCodes.OK).json({
    user: {
      id: user._id,
      email: user.email,
      userName: user.userName,
      role: user.role,
    },
  })
}
 
module.exports = { register, login, currentUser }