From 01d50758c5c4609048c9e9319040c039ec062f42 Mon Sep 17 00:00:00 2001 From: devank21 <132289193+devank21@users.noreply.github.com> Date: Sun, 27 Oct 2024 00:47:55 +0530 Subject: [PATCH] Update user-controller.js hactoberfest2024 --- backend/src/controllers/user-controller.js | 120 +++++---------------- 1 file changed, 28 insertions(+), 92 deletions(-) diff --git a/backend/src/controllers/user-controller.js b/backend/src/controllers/user-controller.js index c36b150d..81afa783 100644 --- a/backend/src/controllers/user-controller.js +++ b/backend/src/controllers/user-controller.js @@ -1,5 +1,7 @@ +//in this versio of code i have tried to remove the redundancy from the code and also have tried to improve the efficency to some sort + const { StatusCodes } = require('http-status-codes'); -const bcrypt = require('bcrypt'); // Changed from bcryptjs to bcrypt +const bcrypt = require('bcrypt'); const User = require('../models/User'); const jwt = require('jsonwebtoken'); const { ServerConfig } = require('../config/index'); @@ -9,142 +11,76 @@ const signup = async (req, res) => { const { name, email, password, role } = req.body; if (!name || !email || !password) { - return res.status(StatusCodes.UNPROCESSABLE_ENTITY).json({ - message: 'Not all fields are filled', - success: false - }); + return res.status(StatusCodes.UNPROCESSABLE_ENTITY).json({ message: 'Not all fields are filled', success: false }); } const existingUser = await User.findOne({ email }); if (existingUser) { - return res.status(StatusCodes.CONFLICT).json({ - message: 'User with the same email already exists', - success: false - }); + return res.status(StatusCodes.CONFLICT).json({ message: 'User with the same email already exists', success: false }); } - // Generate a salt and hash the password - const saltRounds = 12; // Increased from 10 to 12 for better security - const salt = await bcrypt.genSalt(saltRounds); - const hashedPassword = await bcrypt.hash(password, salt); - - const newUser = await User.create({ - name: name, - email: email, - role: role, - password: hashedPassword, - }); - - return res.status(StatusCodes.CREATED).json({ - message: 'User created', - success: true, - id: newUser._id - }); + const hashedPassword = await bcrypt.hash(password, 12); + const newUser = await User.create({ name, email, role, password: hashedPassword }); + return res.status(StatusCodes.CREATED).json({ message: 'User created', success: true, id: newUser._id }); } catch (err) { - return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ - success: false, - message: err.message - }); + return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ success: false, message: err.message }); } }; const login = async (req, res) => { try { const { email, password } = req.body; - if (!email || !password) { - return res.status(StatusCodes.UNPROCESSABLE_ENTITY).json({ - message: 'Not all fields are filled', - success: false - }); - } - let user = await User.findOne({ email }); - if (!user) { - return res.status(StatusCodes.UNAUTHORIZED).json({ - message: 'Email or password incorrect', - success: false - }); + if (!email || !password) { + return res.status(StatusCodes.UNPROCESSABLE_ENTITY).json({ message: 'Not all fields are filled', success: false }); } - const isPasswordCorrect = await bcrypt.compare(password, user.password); - if (!isPasswordCorrect) { - return res.status(StatusCodes.UNAUTHORIZED).json({ - success: false, - message: 'Email or password incorrect', - }); + const user = await User.findOne({ email }); + if (!user || !(await bcrypt.compare(password, user.password))) { + return res.status(StatusCodes.UNAUTHORIZED).json({ message: 'Email or password incorrect', success: false }); } const accessToken = jwt.sign({ userId: user._id }, ServerConfig.JWT_KEY, { subject: 'accessApi', expiresIn: ServerConfig.TOKEN_EXP }); res.cookie('access_token', accessToken, { httpOnly: true, - secure: process.env.NODE_ENV === 'production', // Only send cookie over HTTPS in production - sameSite: 'strict', // Protect against CSRF - maxAge: 3600000 // 1 hour + secure: process.env.NODE_ENV === 'production', + sameSite: 'strict', + maxAge: 3600000 }); - return res.status(StatusCodes.OK).json({ - success: true, - message: "Login successful", - id: user._id, - }); + return res.status(StatusCodes.OK).json({ success: true, message: "Login successful", id: user._id }); } catch (err) { - return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ - success: false, - message: err.message - }); + return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ success: false, message: err.message }); } }; const logout = async (req, res) => { try { res.clearCookie('access_token'); - res.status(StatusCodes.NO_CONTENT).json({ - message: "User logged out successfully" - }); + return res.status(StatusCodes.NO_CONTENT).json({ message: "User logged out successfully" }); } catch (err) { - return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ - success: false, - message: err.message - }); + return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ success: false, message: err.message }); } }; const AdminSection = async (req, res) => { try { - const user = await User.findById({ _id: req.user.id }); - return res.status(StatusCodes.OK).json({ - message: "Welcome to the admin route", - name: user.name, - email: user.email - }); + const user = await User.findById(req.user.id); + return res.status(StatusCodes.OK).json({ message: "Welcome to the admin route", name: user.name, email: user.email }); } catch (err) { - return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ - success: false, - message: err.message - }); + return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ success: false, message: err.message }); } }; const deleteAllUsers = async (req, res) => { try { - const users = await User.deleteMany({}); - return res.status(StatusCodes.OK).json({ - message: "Deleted all the users" - }); + await User.deleteMany({}); + return res.status(StatusCodes.OK).json({ message: "Deleted all the users" }); } catch (err) { - return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ - success: false, - message: err.message - }); + return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ success: false, message: err.message }); } }; -module.exports = { - signup: signup, - login: login, - logout: logout, - AdminSection: AdminSection, - deleteAllUsers: deleteAllUsers -}; \ No newline at end of file +module.exports = { signup, login, logout, AdminSection, deleteAllUsers };