Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Update user-controller.js #1574

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 28 additions & 92 deletions backend/src/controllers/user-controller.js
Original file line number Diff line number Diff line change
@@ -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');
Expand All @@ -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
};
module.exports = { signup, login, logout, AdminSection, deleteAllUsers };
Loading