fcsc_ipi_backend/app/controllers/user.controller.js

166 lines
5.1 KiB
JavaScript

const db = require("../models");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const logger = require("../services/logger");
require("dotenv").config();
const User = db.user;
const EstablishmentUser = db.EstablishmentUser;
// Create User
exports.createUser = async (req, res) => {
try {
const { name, email, password } = req.body;
const existingUser = await User.findOne({ where: { email, is_active: true } });
const establishmentExist = await EstablishmentUser.findOne({ where: { email, is_active: true }});
if (existingUser) {
logger.warn(`Email already exists: ${email}`);
return res.status(409).send({
status: "failed",
message: "Email already exists"
});
}
if (establishmentExist) {
logger.warn(`Email already exists in Company Profile: ${email}`);
return res.status(409).send({
status: "failed",
message: "This email address is already registered in the company profile."
});
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({ name, email, password: hashedPassword });
logger.info("User created successfully");
res.status(201).send({'status':"success",'message':"User created successfully" });
} catch (err) {
logger.error(err.message);
logger.error(`Stack trace: ${err.stack}`);
res.status(500).send({'status':"failed",'message': "Internal server error" });
}
};
// Get All Users
exports.getAllUsers = async (req, res) => {
try {
const users = await User.findAll();
res.status(200).send({'status':"success",'message':"Fetched successfully",'data': users });
} catch (err) {
logger.error(err.message);
logger.error(`Stack trace: ${err.stack}`);
res.status(500).send({'status':"failed",'message': "Internal server error" });
}
};
// Get User by ID
exports.getUserById = async (req, res) => {
try {
const user = await User.findByPk(req.params.id);
if (!user) res.status(404).send({'status':"failed",'message':"Record Not found",'data': "" });
res.status(200).send({'status':"success",'message':"Fetched successfully",'data': user });
} catch (err) {
logger.error(err.message);
logger.error(`Stack trace: ${err.stack}`);
res.status(500).send({'status':"failed",'message': "Internal server error" });
}
};
// Update User
exports.updateUser = async (req, res) => {
try {
const { name, email,is_active } = req.body;
if (email === 'bhavinkumar.chandulal@fcsc.gov.ae') {
return res.status(403).json({
status: "error",
message: "You cannot modify Super Admin data."
});
}
const [updated] = await User.update({ name, email, is_active}, { where: { id: req.params.id } });
if (updated) {
const updatedUser = await User.findByPk(req.params.id);
res.status(200).send({'status':"success",'message':"Updated successfully" });
} else {
res.status(404).send({'status':"failed",'message':"Record Not found" });
}
} catch (err) {
logger.error(err.message);
logger.error(`Stack trace: ${err.stack}`);
res.status(500).send({'status':"failed",'message':"Internal server error" });
}
};
// Delete User
exports.deleteUser = async (req, res) => {
try {
const deleted = await User.destroy({ where: { id: req.params.id } });
if (deleted) {
res.status(200).send({'status':"success",'message':"Deleted successfully",'data': "" });
} else {
res.status(404).send({'status':"failed",'message':"Record Not found",'data': "" });
}
} catch (err) {
logger.error(err.message);
logger.error(`Stack trace: ${err.stack}`);
res.status(500).send({'status':"failed",'message': 'Internal server error' });
}
};
// Change User Password
exports.changeAdminUserPassword = async (req, res) => {
try {
const { old_password, new_password, confirm_password } = req.body;
const userId = req.params.id;
// Validate inputs
if (!old_password || !new_password || !confirm_password) {
return res.status(400).send({ status: "failed", message: "All password fields are required" });
}
if (new_password !== confirm_password) {
return res.status(400).send({ status: "failed", message: "New password and confirm password do not match" });
}
// Find user
const user = await User.scope("withSensitive").findByPk(userId);
if (!user) {
return res.status(404).send({ status: "failed", message: "User not found" });
}
// Verify old password
const isMatch = await bcrypt.compare(old_password, user.password);
if (!isMatch) {
return res.status(400).send({ status: "failed", message: "Old password is incorrect" });
}
// Hash and update new password
const hashedPassword = await bcrypt.hash(new_password, 10);
await User.update(
{ password: hashedPassword },
{ where: { id: userId } }
);
return res.status(200).send({status: "success", message: "Password updated successfully",});
} catch (err) {
logger.error(err.message);
logger.error(`Stack trace: ${err.stack}`);
return res.status(500).send({ status: "failed", message: "Internal server error" });
}
};