|
| 1 | +// controllers/authController.js |
| 2 | + |
| 3 | +const bcrypt = require('bcrypt'); |
| 4 | +const passport = require('passport'); |
| 5 | +const User = require('../models/User'); |
| 6 | +const validator = require('validator'); |
| 7 | + |
| 8 | +//Register |
| 9 | +exports.register = async (req, res) => { |
| 10 | + const { name, username, password } = req.body; |
| 11 | + |
| 12 | + try { |
| 13 | + // Input validation |
| 14 | + if (!name || !username || !password) { |
| 15 | + return res.status(400).json({ message: 'Missing required fields' }); |
| 16 | + } |
| 17 | + |
| 18 | + if (!validator.isEmail(username)) { |
| 19 | + return res.status(400).json({ message: 'Invalid email format' }); |
| 20 | + } |
| 21 | + |
| 22 | + // Password complexity validation (e.g., at least 8 characters with numbers and letters) |
| 23 | + const passwordRegex = /^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/; |
| 24 | + if (!passwordRegex.test(password)) { |
| 25 | + return res.status(400).json({ |
| 26 | + message: |
| 27 | + 'Password must be at least 8 characters long and contain both letters and numbers', |
| 28 | + }); |
| 29 | + } |
| 30 | + // Check if the user already exists |
| 31 | + const existingUser = await User.findOne({ username }); |
| 32 | + if (existingUser) { |
| 33 | + return res.status(409).json({ message: 'User Already Exists' }); |
| 34 | + } |
| 35 | + |
| 36 | + // Hash the password |
| 37 | + const hashedPassword = await bcrypt.hash(password, 10); |
| 38 | + |
| 39 | + // Create a new user |
| 40 | + const user = new User({ |
| 41 | + name, |
| 42 | + username, |
| 43 | + password: hashedPassword, |
| 44 | + }); |
| 45 | + |
| 46 | + // Save the user to the database |
| 47 | + await user.save(); |
| 48 | + |
| 49 | + // Respond with the created user object |
| 50 | + res.status(201).json(user); |
| 51 | + } catch (error) { |
| 52 | + console.error(error); |
| 53 | + |
| 54 | + // Handle specific error scenarios |
| 55 | + if (error.name === 'ValidationError') { |
| 56 | + return res |
| 57 | + .status(400) |
| 58 | + .json({ message: 'Validation Error', details: error.message }); |
| 59 | + } |
| 60 | + |
| 61 | + // For other errors, respond with a generic error message |
| 62 | + res.status(500).json({ message: 'Server error' }); |
| 63 | + } |
| 64 | +}; |
| 65 | + |
| 66 | +//Login |
| 67 | +exports.login = (req, res, next) => { |
| 68 | + // eslint-disable-next-line no-unused-vars |
| 69 | + passport.authenticate('local', (err, user, info) => { |
| 70 | + if (err) { |
| 71 | + console.error(err); |
| 72 | + return res.status(500).json({ message: 'Server error' }); |
| 73 | + } |
| 74 | + if (!user) { |
| 75 | + return res.status(401).json({ message: 'Invalid credentials' }); |
| 76 | + } |
| 77 | + req.logIn(user, (err) => { |
| 78 | + if (err) { |
| 79 | + console.error(err); |
| 80 | + return res.status(500).json({ message: 'Server error' }); |
| 81 | + } |
| 82 | + res.status(200).json(user); |
| 83 | + }); |
| 84 | + })(req, res, next); |
| 85 | +}; |
| 86 | + |
| 87 | +// Logout |
| 88 | +// exports.logout = (req, res) => { |
| 89 | +// const loggedOutUser = req.user; // Retrieve the currently logged-in user |
| 90 | + |
| 91 | +// req.logout(function (err) { |
| 92 | +// if (err) { |
| 93 | +// console.error(err); |
| 94 | +// return res.status(500).json({ message: 'Server error' }); |
| 95 | +// } |
| 96 | + |
| 97 | +// // Include the logged-out user information in the response if available |
| 98 | +// if (loggedOutUser) { |
| 99 | +// res.status(200).json({ |
| 100 | +// message: 'Logged out successfully', |
| 101 | +// user: loggedOutUser, |
| 102 | +// }); |
| 103 | +// } else { |
| 104 | +// res.status(200).json({ message: 'Logged out successfully' }); |
| 105 | +// } |
| 106 | +// }); |
| 107 | +// }; |
| 108 | + |
| 109 | +//Get Single User Details |
| 110 | +// exports.getUserDetails = (req, res) => { |
| 111 | +// const userId = req.params.id; |
| 112 | + |
| 113 | +// User.findById(userId) |
| 114 | +// .then((user) => { |
| 115 | +// if (!user) { |
| 116 | +// return res.status(404).json({ message: 'User not found' }); |
| 117 | +// } |
| 118 | +// res.json(user); |
| 119 | +// }) |
| 120 | +// .catch((error) => { |
| 121 | +// console.error('Failed to get user details', error); |
| 122 | +// res.status(500).json({ message: 'Failed to get user details' }); |
| 123 | +// }); |
| 124 | +// }; |
| 125 | + |
| 126 | +// Get all users list |
| 127 | +exports.getAllUsers = (req, res) => { |
| 128 | + try { |
| 129 | + User.find() |
| 130 | + .then((users) => { |
| 131 | + if (!users || users.length === 0) { |
| 132 | + return res.status(404).json({ message: 'Users not found' }); |
| 133 | + } |
| 134 | + res.json(users); |
| 135 | + }) |
| 136 | + .catch((error) => { |
| 137 | + console.error('Failed to get users list', error); |
| 138 | + res.status(500).json({ message: 'Failed to get users list' }); |
| 139 | + }); |
| 140 | + } catch (error) { |
| 141 | + console.error('Error fetching users', error); |
| 142 | + res.status(500).json({ message: 'Server error' }); |
| 143 | + } |
| 144 | +}; |
| 145 | + |
| 146 | +//Update Password |
| 147 | +// exports.updatePassword = async (req, res) => { |
| 148 | +// const userId = req.params.id; |
| 149 | +// const { currentPassword, newPassword } = req.body; |
| 150 | + |
| 151 | +// try { |
| 152 | +// const user = await User.findById(userId); |
| 153 | +// if (!user) { |
| 154 | +// return res.status(404).json({ message: 'User not found' }); |
| 155 | +// } |
| 156 | + |
| 157 | +// const isMatch = await bcrypt.compare(currentPassword, user.password); |
| 158 | +// if (!isMatch) { |
| 159 | +// return res |
| 160 | +// .status(401) |
| 161 | +// .json({ message: 'Incorrect current password' }); |
| 162 | +// } |
| 163 | + |
| 164 | +// const hashedPassword = await bcrypt.hash(newPassword, 10); |
| 165 | +// user.password = hashedPassword; |
| 166 | +// await user.save(); |
| 167 | + |
| 168 | +// res.json({ message: 'Password updated successfully' }); |
| 169 | +// } catch (error) { |
| 170 | +// console.error('Failed to update password', error); |
| 171 | +// res.status(500).json({ message: 'Failed to update password' }); |
| 172 | +// } |
| 173 | +// }; |
| 174 | + |
| 175 | +//Update User Details |
| 176 | +exports.updateUserDetails = async (req, res) => { |
| 177 | + const { name, username, password } = req.body; |
| 178 | + const userId = req.params.id; |
| 179 | + console.log(userId) |
| 180 | + if(name) console.log(name) |
| 181 | + if(username) console.log(username) |
| 182 | + if(password)console.log(password) |
| 183 | + |
| 184 | + try { |
| 185 | + // Find the user by the provided userId |
| 186 | + const user = await User.findById(userId); |
| 187 | + if (!user) { |
| 188 | + return res.status(404).json({ message: 'User not found' }); |
| 189 | + } |
| 190 | + |
| 191 | + // Update the user details |
| 192 | + user.name = name; |
| 193 | + user.username = username; |
| 194 | + |
| 195 | + // Check if the password field is provided and not empty |
| 196 | + if (password && password.trim() !== '') { |
| 197 | + // Hash the new password and update it |
| 198 | + const hashedPassword = await bcrypt.hash(password, 10); |
| 199 | + user.password = hashedPassword; |
| 200 | + } |
| 201 | + |
| 202 | + // Save the updated user to the database |
| 203 | + await user.save(); |
| 204 | + |
| 205 | + res.json({ message: 'User details updated successfully' }); |
| 206 | + } catch (error) { |
| 207 | + console.error('Failed to update user:', error); |
| 208 | + res.status(500).json({ message: 'Failed to update user details' }); |
| 209 | + } |
| 210 | +}; |
| 211 | + |
| 212 | +//Delete User |
| 213 | +// DELETE /users/:userId - Delete a user by their userId |
| 214 | +exports.deleteUser = async (req, res) => { |
| 215 | + const userId = req.params.id; |
| 216 | + |
| 217 | + try { |
| 218 | + // Find the user by the provided userId |
| 219 | + const user = await User.findById(userId); |
| 220 | + if (!user) { |
| 221 | + return res.status(404).json({ message: 'User not found' }); |
| 222 | + } |
| 223 | + |
| 224 | + // Delete the user from the database |
| 225 | + await user.deleteOne(); // Or use await User.deleteOne({ _id: userId }); directly |
| 226 | + |
| 227 | + res.json({ message: 'User deleted successfully' }); |
| 228 | + } catch (error) { |
| 229 | + console.error('Failed to delete user:', error); |
| 230 | + res.status(500).json({ message: 'Failed to delete user' }); |
| 231 | + } |
| 232 | +}; |
0 commit comments