narinder1231's picture
improve error logging and error messages
d747060
import { Request, Response } from 'express';
import User from '../models/users';
import { AuthenticatedRequest, UserInterface } from '../shared/interfaces/user.interface';
import { hashPassword } from '../utils/passwordUtils';
import { FindOptions, Op } from 'sequelize';
import { logger } from '../utils/logger';
import Role from '../models/roles';
import { sendMail } from '../utils/mailer';
import RolePermission from '../models/rolePermissions';
import Permission from '../models/permissions';
import { JwtPayload } from 'jsonwebtoken';
const createUser = async (req: Request, res: Response) => {
try {
const { name, email, role_id, status, password } = req.body;
const hashedPassword = await hashPassword(password);
const newUser: UserInterface = {
name,
email,
role_id,
status,
password: hashedPassword,
};
const createdUser = await User.create(newUser);
const userResponse = {
id: createdUser.id,
name: createdUser.name,
email: createdUser.email,
status: createdUser.status,
role_id: createdUser.role_id,
};
sendMail({
subject: 'Welcome to Fusion Bills - Your Account Has Been Created',
to: email,
content: `<p>Hi <b>${name},</b></p>
<p>Welcome to Fusion Bills. We’re excited to have you on board.</p>
<p>Your account has been created by an administrator. Here are your login credentials:</p>
<ul>
<li><strong>Username:</strong> ${email}</li>
<li><strong>Password:</strong> ${password}</li>
</ul>
<p>You can log in to your account at <a href="${process.env.APP_URL}">${process.env.APP_URL}</a> using these credentials. We recommend changing your password after logging in for the first time to keep your account secure.</p>
<p>If you have any questions or need assistance, feel free to reach out to our support team.</p>
<p>Best regards,<br>Team Fusion Bills</p>
`
})
return res.status(201).json({
message: 'User created successfully',
data: userResponse,
});
} catch (error) {
logger.error("Error creating a User:", error);
return res.status(500).json({
error: 'Error while creating a User.',
});
}
};
const getUserById = async (req: Request, res: Response) => {
try {
const userId = req.params.id
const user = await User.findByPk(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const userResponse = {
id: user.id,
name: user.name,
email: user.email,
status: user.status,
role_id: user.role_id,
};
return res.status(200).json(userResponse);
} catch (error) {
logger.error('Error fetching user:', error);
return res.status(500).json({ error: 'Error while fetching User details.' });
}
};
const buildUserWhereClause = (filter: Record<string, any>): any => {
const whereClause: any = {};
if (filter) {
if (filter.name) {
whereClause.name = { [Op.like]: `%${filter.name}%` };
}
if (filter.email) {
whereClause.email = { [Op.like]: `%${filter.email}%` };
}
if (filter.id) {
whereClause.id = { [Op.eq]: filter.id };
}
if (filter.date) {
const date = new Date(filter.date);
if (!isNaN(date.getTime())) {
const startOfDay = new Date(date);
startOfDay.setHours(0, 0, 0, 0);
const endOfDay = new Date(date);
endOfDay.setHours(23, 59, 59, 999);
whereClause.created_at = {
[Op.gte]: startOfDay,
[Op.lte]: endOfDay
};
}
}
if (filter.role_id) {
whereClause.role_id = { [Op.eq]: filter.role_id };
}
if (filter.status) {
whereClause.status = { [Op.eq]: filter.status };
}
if (filter.created_before) {
const beforeDate = new Date(filter.created_before);
if (!isNaN(beforeDate.getTime())) {
whereClause.created_at = { ...whereClause.created_at, [Op.lte]: beforeDate };
}
}
if (filter.created_after) {
const afterDate = new Date(filter.created_after);
if (!isNaN(afterDate.getTime())) {
whereClause.created_at = { ...whereClause.created_at, [Op.gte]: afterDate };
}
}
}
return whereClause;
};
const getAllUsers = async (req: Request, res: Response) => {
try {
const { sort_by, sort_order, page, limit } = req.query;
const filter = req.query.filter as Record<string, any>;
const allowedSortColumns = ['id', 'name', 'email', 'role_id', 'created_at', 'status'];
const whereClause = buildUserWhereClause(filter);
const currentPage = parseInt(page as string) || 1;
const pageSize = parseInt(limit as string) || 10;
const options: FindOptions = {
where: whereClause,
attributes: { exclude: ['password'] },
limit: pageSize,
offset: (currentPage - 1) * pageSize,
order: []
};
if (sort_by && allowedSortColumns.includes(sort_by as string)) {
options.order = [[sort_by as string, sort_order === 'desc' ? 'DESC' : 'ASC']];
} else {
options.order = [['id', 'DESC']];
}
const [users, totalUsers] = await Promise.all([
User.findAll({
...options, include: [{ model: Role, as: 'role' }
]
}),
User.count({ where: whereClause }),
]);
const responseData = {
page: currentPage,
limit: pageSize,
total: totalUsers,
data: users
};
return res.status(200).json(responseData);
} catch (error) {
logger.error('Error fetching users:', error);
return res.status(500).json({ error: 'Error fetching users.' });
}
};
const updateUserById = async (req: Request, res: Response) => {
try {
const userId = parseInt(req.params.id, 10);
const { name, email, role_id, status, password } = req.body;
const user = await User.findByPk(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
let isEmailUpdated = false;
let isPasswordUpdated = false;
if (name) {
user.name = name;
}
if (email && email !== user.email) {
sendMail({
subject: 'Important: Your Email Address Has Been Updated',
to: user.email,
content: `<p>Hi <b>${name},</b></p>
<p>We wanted to inform you that the email address associated with your account has been updated.
From now on, you will need to use your new email address:<strong> ${email} </strong> to log in. Your password remains the same, so you can continue using your current password to access your account.
All future notifications, updates, and important communications will be sent to this new email address. If you did not request this change or believe this to be a mistake, please contact us immediately.
If you have any questions or concerns, feel free to reach out to our support team.</p>
<p>Thank you for your attention.</p>
<p>Best regards,<br>Team Fusion Bills</p>`
});
user.email = email;
isEmailUpdated = true;
}
if (role_id) {
user.role_id = role_id;
}
if (status) {
user.status = status;
}
if (password) {
const hashedPassword = await hashPassword(password);
if (hashedPassword !== user.password) {
user.password = hashedPassword;
isPasswordUpdated = true;
}
}
await user.save();
const userResponse = {
id: user.id,
name: user.name,
email: user.email,
status: user.status,
role_id: user.role_id,
};
let content = isEmailUpdated && isPasswordUpdated ?
`<p>Hi <b>${name},</b></p>
<p>We’re writing to confirm that both your email address and password have been updated.</p>
<p>Your new login details are:</p>
<ul>
<li><strong>Email:</strong> ${email}</li>
<li><strong>Password:</strong> ${password}</li>
</ul>
<p>You can now use these credentials to log in at <a href="${process.env.APP_URL}">${process.env.APP_URL}</a></p>
<p>If you did not request these changes or believe this to be a mistake, please contact us immediately to secure your account.</p>
<p>For security, we recommend updating your password regularly and avoiding sharing your login information with anyone.</p>
<p>If you need any further assistance, feel free to reach out to our support team.</p>
<p>Best regards,<br>Team Fusion Bills</p>`
: isPasswordUpdated ?
`<p>Hi <b>${name},</b></p>
<p>We wanted to inform you that an administrator has updated your account password.</p>
<p>Your new password is:<strong> ${password}</strong>.</p>
<p>Please use this new password to log in to your account at <a href="${process.env.APP_URL}">${process.env.APP_URL}</a>.</p>
<p>For security purposes, we recommend changing this password after logging in. If you did not request this change or believe this to be a mistake, please contact us immediately.</p>
<p>If you have any questions or need assistance, feel free to reach out to our support team.</p>
<p>Best regards,<br>Team Fusion Bills</p>` :
`<p>Hi <b>${name},</b></p>
<p>We’re happy to confirm that your email address has been updated to <strong> ${email} </strong>.
From now on, you can use this new email address to log in to your account, while keeping your current password. All future notifications and communications will also be sent to this address.
If you did not request this change or believe this to be a mistake, please contact us immediately.
Thank you for staying with us! If you have any questions or need further assistance, our support team is here to help.</p>
<p>Best regards,<br>Team Fusion Bills</p>`
let subject = isEmailUpdated && isPasswordUpdated ?
`Fusion Bills - Your Email and Password Have Been Updated`
: isPasswordUpdated ?
`Fusion Bills - Your Password Has Been Successfully Updated` :
`Welcome to Fusion Bills - Your Email Address Has Been Updated`
if (isEmailUpdated || isPasswordUpdated) {
sendMail({
subject: subject,
to: user.email,
content: content
});
}
return res.status(200).json(userResponse);
} catch (error) {
logger.error('Error updating user:', error);
return res.status(500).json({ error: 'Internal server error' });
}
};
const deleteUserById = async (req: Request, res: Response) => {
try {
const userId = parseInt(req.params.id, 10);
const deletedRowCount = await User.destroy({
where: { id: userId },
});
if (deletedRowCount === 0) {
return res.status(404).json({ error: 'User not found' });
}
return res.status(204).send();
} catch (error) {
logger.error('Error deleting user:', error);
return res.status(500).json({ error: 'Error while deleting User.' });
}
};
const getCurrentUser = async (req: AuthenticatedRequest, res: Response) => {
try {
const user = req.user as JwtPayload;
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const userData = await User.findByPk(user.id, {
include: [
{
model: Role,
as: 'role',
include: [
{
model: Permission,
as: 'permissions',
through: {
attributes: [],
},
},
],
},
],
});
return res.status(200).json({
user: userData
});
} catch (error) {
logger.error('Error fetching user:');
logger.error(error);
return res.status(500).json({ error: 'Error while fetching User details.' });
}
};
export { createUser, getUserById, getAllUsers, deleteUserById, updateUserById, getCurrentUser };