Skip to content
Merged
Show file tree
Hide file tree
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
13 changes: 7 additions & 6 deletions controller/appointmentController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const {addAppointment, addAppointmentModelV2, updateAppointmentModel, deleteAppointmentById} = require('../model/appointmentModel.js');
const {getAllAppointments, getAllAppointmentsV2 } = require('../model/getAppointments.js');
const logger = require('../utils/logger');
const { validationResult } = require('express-validator');


Expand All @@ -20,7 +21,7 @@ const saveAppointment = async (req, res) => {
// Respond with success message if appointment data is successfully saved
res.status(201).json({ message: 'Appointment saved successfully' });//, appointmentId: result.id
} catch (error) {
console.error('Error saving appointment:', error);
logger.error('Error saving appointment', { error: error.message, userId });
res.status(500).json({ error: 'Internal server error' });
}
};
Expand Down Expand Up @@ -65,7 +66,7 @@ const saveAppointmentV2 = async (req, res) => {
appointment,
});
} catch (error) {
console.error("Error saving appointment:", error);
logger.error('Error saving appointment (V2)', { error: error.message, userId });
res.status(500).json({ error: "Internal server error" });
}
};
Expand Down Expand Up @@ -114,7 +115,7 @@ const updateAppointment = async (req,res)=>{
appointment: updatedAppointment,
});
} catch (error) {
console.error('Error updating appointment:', error);
logger.error('Error updating appointment', { error: error.message, appointmentId: id });
res.status(500).json({ error: 'Internal server error' });
}
}
Expand All @@ -133,7 +134,7 @@ const delAppointment = async (req,res)=>{
message: 'Appointment deleted successfully',
});
} catch (error) {
console.error('Error deleting appointment:', error);
logger.error('Error deleting appointment', { error: error.message, appointmentId: id });
res.status(500).json({ error: 'Internal server error' });
}
}
Expand All @@ -149,7 +150,7 @@ const getAppointments = async (req, res) => {
// Respond with the retrieved appointment data
res.status(200).json(appointments);
} catch (error) {
console.error('Error retrieving appointments:', error);
logger.error('Error retrieving appointments', { error: error.message });
res.status(500).json({ error: 'Internal server error' });
}
};
Expand All @@ -174,7 +175,7 @@ const getAppointmentsV2 = async (req, res) => {
appointments
});
} catch (error) {
console.error("Error retrieving appointments:", error);
logger.error('Error retrieving appointments (V2)', { error: error.message });
res.status(500).json({ error: "Internal server error" });
}
};
Expand Down
16 changes: 12 additions & 4 deletions controller/authController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const authService = require('../services/authService');
const { isServiceError } = require('../services/serviceError');
const logger = require('../utils/logger');

const TRUSTED_DEVICE_COOKIE = authService.trustedDeviceCookieName || 'trusted_device';

Expand Down Expand Up @@ -31,7 +32,7 @@ function handleServiceError(res, error, fallbackStatus, fallbackLogLabel) {
});
}

console.error(fallbackLogLabel, error);
logger.error(fallbackLogLabel, { error: error.message });
return res.status(fallbackStatus).json({
success: false,
error: error.message || 'Internal server error'
Expand All @@ -50,6 +51,7 @@ exports.register = async (req, res) => {

return res.status(201).json(result);
} catch (error) {
logger.error('Registration error', { error: error.message, email: req.body.email });
return handleServiceError(res, error, 400, 'Registration error:');
}
};
Expand All @@ -63,6 +65,7 @@ exports.login = async (req, res) => {

return res.json(result);
} catch (error) {
logger.error('Login error', { error: error.message, email: req.body.email });
return handleServiceError(res, error, 401, 'Login error:');
}
};
Expand All @@ -72,6 +75,7 @@ exports.refreshToken = async (req, res) => {
const result = await authService.refreshAccessToken(req.body.refreshToken, getDeviceInfo(req));
return res.json(result);
} catch (error) {
logger.error('Token refresh error', { error: error.message });
return handleServiceError(res, error, 401, 'Token refresh error:');
}
};
Expand All @@ -81,6 +85,7 @@ exports.logout = async (req, res) => {
const result = await authService.logout(req.body.refreshToken);
return res.json(result);
} catch (error) {
logger.error('Logout error', { error: error.message, userId: req.user?.userId });
return handleServiceError(res, error, 500, 'Logout error:');
}
};
Expand All @@ -95,6 +100,7 @@ exports.logoutAll = async (req, res) => {
clearTrustedDeviceCookie(res);
return res.json(result);
} catch (error) {
logger.error('Logout all error', { error: error.message, userId: req.user?.userId });
return handleServiceError(res, error, 500, 'Logout all error:');
}
};
Expand All @@ -114,6 +120,7 @@ exports.revokeTrustedDevices = async (req, res) => {
revokedCount: result.revokedCount
});
} catch (error) {
logger.error('Revoke trusted devices error', { error: error.message, userId: req.user?.userId });
return handleServiceError(res, error, 500, 'Revoke trusted devices error:');
}
};
Expand All @@ -123,6 +130,7 @@ exports.getProfile = async (req, res) => {
const result = await authService.getProfile(req.user.userId);
return res.json(result);
} catch (error) {
logger.error('Get profile error', { error: error.message, userId: req.user?.userId });
return handleServiceError(res, error, 500, 'Get profile error:');
}
};
Expand All @@ -143,7 +151,7 @@ exports.logLoginAttempt = async (req, res) => {
return res.status(error.statusCode).json({ error: error.message });
}

console.error('Failed to insert login log:', error);
logger.error('Failed to insert login log', { error: error.message, email: req.body.email });
return res.status(500).json({ error: 'Failed to log login attempt' });
}
};
Expand All @@ -157,7 +165,7 @@ exports.sendSMSByEmail = async (req, res) => {
return res.status(error.statusCode).json({ error: error.message });
}

console.error('Error sending SMS:', error);
logger.error('Error sending SMS', { error: error.message, email: req.body.email });
return res.status(500).json({ error: 'Internal server error' });
}
};
};
29 changes: 21 additions & 8 deletions controller/chatbotController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { chatbotService } = require('../services/chatbotService');
const { isServiceError } = require('../services/serviceError');
const logger = require('../utils/logger');

function serviceErrorToPayload(error) {
return {
Expand All @@ -8,8 +9,8 @@ function serviceErrorToPayload(error) {
};
}

function handleUnexpectedError(res, label, error) {
console.error(`${label}:`, error);
function handleUnexpectedError(res, label, error, context = {}) {
logger.error(label, { error: error.message, ...context });
return res.status(500).json({
error: 'Internal server error',
details: process.env.NODE_ENV === 'development' ? error.message : undefined
Expand All @@ -28,7 +29,9 @@ async function getChatResponse(req, res) {
return res.status(error.statusCode).json(serviceErrorToPayload(error));
}

return handleUnexpectedError(res, 'Error in chatbot response', error);
return handleUnexpectedError(res, 'Error in chatbot response', error, {
userId: req.body.user_id
});
}
}

Expand All @@ -41,7 +44,9 @@ async function addURL(req, res) {
return res.status(error.statusCode).json({ error: error.message });
}

return handleUnexpectedError(res, 'Error processing URL', error);
return handleUnexpectedError(res, 'Error processing URL', error, {
urls: req.body.urls
});
}
}

Expand All @@ -50,7 +55,11 @@ async function addPDF(req, res) {
const result = await chatbotService.addPdf(req.body.pdfs);
return res.status(result.statusCode).json(result.body);
} catch (error) {
return handleUnexpectedError(res, 'Error in chatbot response', error);
if (isServiceError(error)) {
return res.status(error.statusCode).json({ error: error.message });
}

return handleUnexpectedError(res, 'Error processing PDF', error);
}
}

Expand All @@ -63,7 +72,9 @@ async function getChatHistory(req, res) {
return res.status(error.statusCode).json(serviceErrorToPayload(error));
}

return handleUnexpectedError(res, 'Error retrieving chat history', error);
return handleUnexpectedError(res, 'Error retrieving chat history', error, {
userId: req.body.user_id
});
}
}

Expand All @@ -76,7 +87,9 @@ async function clearChatHistory(req, res) {
return res.status(error.statusCode).json(serviceErrorToPayload(error));
}

return handleUnexpectedError(res, 'Error clearing chat history', error);
return handleUnexpectedError(res, 'Error clearing chat history', error, {
userId: req.body.user_id
});
}
}

Expand All @@ -86,4 +99,4 @@ module.exports = {
addPDF,
getChatHistory,
clearChatHistory
};
};
17 changes: 9 additions & 8 deletions controller/homeServiceController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const supabase = require("../dbConnection.js");
const logger = require('../utils/logger');
const {
createServiceModel,
updateServiceModel,
Expand All @@ -17,15 +18,15 @@ const getServiceContents = async (req, res) => {
.select("title, description, image");

if (error) {
console.error("Error get service contents:", error.message);
logger.error('Error getting service contents', { error: error.message });
return res.status(500).json({ error: "Failed to get service contents" });
}

return res
.status(200)
.json({ message: "Get service contents successfully", data });
} catch (error) {
console.error("Internal server error:", error.message);
logger.error('Internal server error in getServiceContents', { error: error.message });
return res.status(500).json({ error: "Internal server error" });
}
};
Expand Down Expand Up @@ -62,7 +63,7 @@ const getServiceContentsPage = async (req, res) => {
const { data, error, count } = await query;

if (error) {
console.error("Error getting service contents:", error.message);
logger.error('Error getting service contents', { error: error.message });
return res.status(500).json({ error: "Failed to get service contents" });
}

Expand All @@ -75,7 +76,7 @@ const getServiceContentsPage = async (req, res) => {
data,
});
} catch (error) {
console.error("Internal server error:", error.message);
logger.error('Internal server error in getServiceContentsPage', { error: error.message });
return res.status(500).json({ error: "Internal server error" });
}
};
Expand All @@ -100,7 +101,7 @@ const createService = async (req, res) => {
data: service,
});
} catch (error) {
console.error("Error creating service:", error.message);
logger.error('Error creating service', { error: error.message });
res.status(500).json({ error: error.message });
}
};
Expand All @@ -126,7 +127,7 @@ const updateService = async (req, res) => {
data: service,
});
} catch (error) {
console.error("Error updating service:", error.message);
logger.error('Error updating service', { error: error.message, serviceId: req.params.id });
res.status(500).json({ error: error.message });
}
};
Expand All @@ -145,7 +146,7 @@ const deleteService = async (req, res) => {
message: "Service deleted successfully",
});
} catch (error) {
console.error("Error deleting service:", error.message);
logger.error('Error deleting service', { error: error.message, serviceId: req.params.id });
res.status(500).json({ error: error.message });
}
};
Expand All @@ -167,7 +168,7 @@ const addSubscribe = async (req, res) => {
data: subscribe,
});
} catch (error) {
console.error("Error creating subscribe:", error.message);
logger.error('Error creating subscribe', { error: error.message, email: req.body.email });
res.status(500).json({ error: error.message });
}
};
Expand Down
5 changes: 3 additions & 2 deletions controller/imageClassificationController.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
const fs = require('fs');
const path = require('path');
const logger = require('../utils/logger');
const { executePythonScript } = require('../services/aiExecutionService');

// Utility to delete the uploaded file
const deleteFile = (filePath) => {
fs.unlink(filePath, (err) => {
if (err) {
console.error('Error deleting file:', err);
logger.error('Error deleting image file', { filePath, error: err.message });
}
});
};
Expand Down Expand Up @@ -58,7 +59,7 @@ const predictImage = async (req, res) => {
error: null
});
} catch (error) {
console.error('Error reading image file:', error);
logger.error('Error reading image file', { error: error.message, filePath: imagePath });
return res.status(500).json({
success: false,
prediction: null,
Expand Down
18 changes: 10 additions & 8 deletions controller/loginController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const logger = require('../utils/logger');
const logLoginEvent = require('../Monitor_&_Logging/loginLogger');
const getUserCredentials = require('../model/getUserCredentials.js');
const { addMfaToken, verifyMfaToken } = require('../model/addMfaToken.js');
Expand Down Expand Up @@ -207,7 +208,7 @@ const login = async (req, res) => {
const token = createAccessToken(user);
return res.status(200).json({ user, token });
} catch (err) {
console.error('Login error:', err);
logger.error('Login error', { error: err.message, email });
return res.status(500).json({ error: 'Internal server error' });
}
};
Expand Down Expand Up @@ -259,7 +260,7 @@ const loginMfa = async (req, res) => {
trusted_device: rememberDevice
});
} catch (err) {
console.error('MFA login error:', err);
logger.error('MFA login error', { error: err.message, email });
return res.status(500).json({ error: 'Internal server error' });
}
};
Expand Down Expand Up @@ -293,7 +294,7 @@ const resendMfa = async (req, res) => {
message: 'A new MFA token has been sent to your email address'
});
} catch (err) {
console.error('Resend MFA error:', err);
logger.error('Resend MFA error', { error: err.message, email });
return res.status(500).json({ error: 'Internal server error' });
}
};
Expand All @@ -314,9 +315,9 @@ async function sendOtpEmail(email, token) {
<p>- NutriHelp Security Team</p>
`
});
console.log('OTP email sent successfully to', email);
logger.info('OTP email sent successfully', { email });
} catch (err) {
console.error('Error sending OTP email:', err.message);
logger.error('Error sending OTP email', { error: err.message, email });
}
}

Expand All @@ -335,9 +336,10 @@ async function sendFailedLoginAlert(email, ip) {
<p>- NutriHelp Security Team</p>
`
});
} catch (error) {
console.error('Failed to send alert email:', error.message);
logger.info('Failed login alert sent', { email, ip });
} catch (err) {
logger.error('Failed to send alert email', { error: err.message, email });
}
}

module.exports = { login, loginMfa, resendMfa };
module.exports = { login, loginMfa, resendMfa };
Loading
Loading