Spaces:
Runtime error
Runtime error
File size: 12,411 Bytes
e3ff446 2300112 e3ff446 1abeb29 2c97468 1056391 f1f70bc 2300112 653bf49 e3ff446 653bf49 e3ff446 653bf49 e3ff446 f1f70bc aa94e69 f1f70bc 653bf49 02a3dcb 653bf49 f1f70bc 653bf49 f1f70bc e3ff446 653bf49 e3ff446 653bf49 e3ff446 653bf49 e3ff446 653bf49 e3ff446 653bf49 e3ff446 653bf49 e3ff446 2c97468 e3ff446 1abeb29 b33bbd2 653bf49 b33bbd2 653bf49 331064e 653bf49 331064e 653bf49 1abeb29 653bf49 1abeb29 b33bbd2 1abeb29 b695efe 1abeb29 653bf49 1abeb29 5968265 1abeb29 5968265 1abeb29 5968265 1abeb29 2c97468 1abeb29 9f11419 6a978cd 9f11419 653bf49 f311ea1 9f11419 f1f70bc 653bf49 9f11419 f311ea1 9f11419 6a978cd f1f70bc f311ea1 f1f70bc 6a978cd 9f11419 653bf49 9f11419 653bf49 aa94e69 653bf49 aa94e69 653bf49 f311ea1 f1f70bc 653bf49 f1f70bc 653bf49 f1f70bc 9f11419 2c97468 9f11419 5e8365d 2c97468 5e8365d 2300112 2f7395b 653bf49 2f7395b 2300112 2f7395b 653bf49 2300112 d747060 2300112 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
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 };
|