Skip to content

Commit

Permalink
Update user-controller.js
Browse files Browse the repository at this point in the history
hactoberfest2024
  • Loading branch information
devank21 authored Oct 26, 2024
1 parent ed4f264 commit 01d5075
Showing 1 changed file with 28 additions and 92 deletions.
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 };

0 comments on commit 01d5075

Please sign in to comment.