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 | 2x 2x 2x 2x 3x 3x 3x 1x 2x 2x 1x 1x 1x 1x 1x 2x 3x 3x 3x 1x 2x 2x 2x 2x 1x 1x 1x 2x 2x | const User = require('../users/user.model')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
// @desc Register a new user
// @route POST /api/users
// @access Public
const register = async (req, res) => {
try {
const { userName, email, password } = req.body
if (!userName || !email || !password) {
return res.status(400).json({ message: 'All fields are required' })
}
const userAvailable = await User.findOne({ email })
if (userAvailable) {
return res.status(400).json({ message: 'User already exists' })
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10)
const newUser = new User({
userName,
email,
password: hashedPassword,
role: 'customer', // Default role
})
const savedUser = await newUser.save()
res.status(201).json({
message: 'User registered successfully',
})
} catch (error) {
console.error('Error creating order', error)
res.status(500).json({ message: error.message })
}
}
// @desc Login user
// @route POST /api/users/login
// @access Public
const login = async (req, res) => {
try {
const { email, password } = req.body
if (!email || !password) {
return res
.status(400)
.json({ message: 'Email and password are required' })
}
const user = await User.findOne({ email })
Iif (!user) {
return res.status(401).json({ message: 'Invalid credentials' })
}
const isPasswordValid = await bcrypt.compare(password, user.password)
if (!isPasswordValid) {
return res.status(401).json({ message: 'Invalid credentials' })
}
const accessToken = jwt.sign(
{ user: { id: user._id, role: user.role, userName: user.userName } },
process.env.JWT_SECRET_KEY,
{ expiresIn: '1h' },
)
res.status(200).json({
message: 'Login successful',
accessToken,
})
} catch (error) {
console.error('Error fetching orders', error)
res.status(500).json({ message: error.message })
}
}
// @desc Get current user
// @route GET /api/users/current
// @access Private
const currentUser = async (req, res) => {
try {
const { id } = req.user
const user = await User.findById(id)
if (!user) {
return res.status(404).json({ message: 'User not found' })
}
res.status(200).json(user)
} catch (error) {
console.error('Error fetching user', error)
res.status(500).json({ message: error.message })
}
}
module.exports = { register, login, currentUser }
|