diff --git a/middlewares/PatientAuth.js b/middlewares/PatientAuth.js new file mode 100644 index 0000000..11b980b --- /dev/null +++ b/middlewares/PatientAuth.js @@ -0,0 +1,40 @@ +import jwt from "jsonwebtoken"; +import Patient from "../resources/Patients/PatientModel.js"; + +export const isAuthenticatedPatient = async (req, res, next) => { + try { + if (!req.headers.authorization) { + return res.status(401).json({ + success: false, + message: "Please Login to access this resource", + }); + } + const getToken = req.headers; + //remove Bearer from token + const fronttoken = getToken.authorization.slice(7); + + const frontdecoded = jwt.verify(fronttoken, process.env.JWT_SECRET); + if (!frontdecoded) { + return res.status(400).json({ + success: false, + message: "incorrect token", + }); + } + const fpatient = await Patient.findById(frontdecoded.id); + if (fpatient) { + req.patient = fpatient; + return next(); + } else { + return res.status(401).json({ + success: false, + message: "Unauthorized", + }); + } + } catch (error) { + return res.status(401).json({ + success: false, + message: error.message, + }); + } +}; + diff --git a/resources/Patients/PatientController.js b/resources/Patients/PatientController.js index 45609d0..2dc2763 100644 --- a/resources/Patients/PatientController.js +++ b/resources/Patients/PatientController.js @@ -53,18 +53,15 @@ export const verifyOtp = async (req, res) => { if (patient.otp !== otp || patient.otpExpires < Date.now()) { return res.status(400).json({ message: 'Invalid or expired OTP' }); } - patient.isVerified = true; patient.otp = undefined; patient.otpExpires = undefined; - await patient.save(); - res.cookie('patientId', patient._id.toString(), - { httpOnly: true } - ); // 1 day in milliseconds - // { httpOnly: true, maxAge: 24 * 60 * 60 * 1000 } - - res.status(200).json({ patient, message: 'Mobile number verified successfully' }); + const token = patient.getJWTToken(); + res.status(200).json({ + success: true, + token, message: 'Mobile number verified successfully' + }); } catch (error) { res.status(500).json({ message: error.message ? error.message : "Server error!", @@ -92,18 +89,19 @@ export const loginPatient = async (req, res) => { if (!isPasswordMatched) { return res.status(400).json({ message: "Invalid Email or Password" }); } - await res.cookie('patientId', patient._id.toString(), - { httpOnly: true } - ); - return res.status(200).json({ success: true, message: "Login Successfully" }); + const token = patient.getJWTToken(); + + return res.status(200).json({ success: true, token, message: "Login Successfully" }); } catch (error) { return res .status(500) - .json({ message: "Something went wrong!", error: error?.message || "" }); + .json({ + message: error.message ? error.message : "Something went wrong!", + }); } }; -//get All Product +//get All patient export const getAllPatient = async (req, res) => { try { const PAGE_SIZE = parseInt(req.query?.show || "10"); @@ -161,30 +159,32 @@ export const create1RegistrationDetails = async (req, res) => { if (!validator.isEmail(email)) { return res.status(400).json({ message: 'Invalid email format' }); } - const patientId = req.cookies.patientId; - if (!patientId) { - return res.status(400).json({ message: 'Patient did not registered Or verified' }); - } + if (password !== confirmPassword) { return res.status(400).json({ message: 'Password and confirm password do not match' }); } try { - const patient = await Patient.findById(patientId); - if (!patient || !patient.isVerified) { - return res.status(400).json({ message: 'Patient not found or not verified' }); + const patient = await Patient.findById(req.patient._id); + if (!patient) { + return res.status(404).json({ message: 'Patient not found ' }); + } + if (!patient.isVerified) { + return res.status(400).json({ message: 'Patient not verified' }); } // Check if another patient with the same email exists const emailExists = await Patient.findOne({ email }); - if (emailExists && emailExists._id.toString() !== patientId) { - return res.status(400).json({ message: 'Email is already in use By Another patient' }); + if (emailExists && emailExists._id.toString() !== req.patient._id) { + return res.status(400).json({ message: 'This Email ID is already in use By Another patient' }); } patient.email = email; patient.password = password; await patient.save(); + const patientResponse = patient.toObject(); + delete patientResponse.password; - res.status(200).json({ patient, message: 'Registration details updated successfully' }); + res.status(200).json({ patient: patientResponse, message: 'Registration details updated successfully' }); } catch (error) { res.status(500).json({ @@ -243,15 +243,16 @@ export const EnterPatientDetails = async (req, res) => { if (isNaN(age)) { return res.status(400).json({ message: 'age must be a number' }); } - const patientId = req.cookies.patientId; - if (!patientId) { - return res.status(400).json({ message: 'Patient did not registered Or verified' }); - } + try { - const patient = await Patient.findById(patientId); - if (!patient || !patient.isVerified) { - return res.status(400).json({ message: 'Patient not found or not verified' }); + const patient = await Patient.findById(req.patient._id); + if (!patient) { + return res.status(404).json({ message: 'Patient not found ' }); } + if (!patient.isVerified) { + return res.status(400).json({ message: 'Patient not verified' }); + } + patient.gender = gender; patient.weight = { value: weightValue, @@ -263,7 +264,9 @@ export const EnterPatientDetails = async (req, res) => { }; patient.age = age; await patient.save(); - res.status(200).json({ patient, message: 'Patient details updated successfully' }); + const patientResponse = patient.toObject(); + delete patientResponse.password; + res.status(200).json({ patient: patientResponse, message: 'Patient details updated successfully' }); } catch (error) { res.status(500).json({ @@ -286,11 +289,13 @@ export const EnterPersonalDetails = async (req, res) => { return res.status(400).json({ message: 'Patient did not registered Or verified' }); } try { - const patient = await Patient.findById(patientId); - if (!patient || !patient.isVerified) { - return res.status(400).json({ message: 'Patient not found or not verified' }); + const patient = await Patient.findById(req.patient._id); + if (!patient) { + return res.status(404).json({ message: 'Patient not found ' }); + } + if (!patient.isVerified) { + return res.status(400).json({ message: 'Patient not verified' }); } - // Check if another patient with the same email exists patient.commonHealthComplaints = commonHealthComplaints; @@ -298,7 +303,9 @@ export const EnterPersonalDetails = async (req, res) => { patient.personalHistory = personalHistory; patient.dailyRoutine = dailyRoutine; await patient.save(); - res.status(200).json({ patient, message: 'Patient Pesonal details updated successfully' }); + const patientResponse = patient.toObject(); + delete patientResponse.password; + res.status(200).json({ patient: patientResponse, message: 'Patient Pesonal details updated successfully' }); } catch (error) { res.status(500).json({ @@ -311,7 +318,7 @@ export const EnterPersonalDetails = async (req, res) => { // 4.Forgot Password -export const forgotPassword = async (req, res, next) => { +export const forgotPassword = async (req, res) => { const patient = await Patient.findOne({ email: req.body.email }); if (!req.body.email) { return res.status(400).json({ message: 'please Enter Email!' }); @@ -323,7 +330,7 @@ export const forgotPassword = async (req, res, next) => { // const resetToken = patient.getResetPasswordToken(); //call function //save database reset token - await patient.save({ validateBeforeSave: false }); + // await patient.save({ validateBeforeSave: false }); const passwords = password.randomPassword({ length: 12, @@ -360,7 +367,9 @@ export const forgotPassword = async (req, res, next) => { return res .status(500) - .json({ message: "Something went wrong!", error: error?.message || "" }); + .json({ + message: error.message ? error.message : "Something went wrong!", + }); } }; @@ -369,16 +378,18 @@ export const UploadProfileImage = async (req, res) => { if (!req.files) { return res.status(404).json({ message: "Please Select Image" }); } - // const patientId = req.cookies.patientId; - // console.log(req.params?.patientId) - if (!req.params?.patientId) { - return res.status(400).json({ message: 'Please Provide patientId!' }); + const patient = await Patient.findById(req.patient._id); + if (!patient) { + return res.status(404).json({ message: 'Patient not found ' }); + } + if (!patient.isVerified) { + return res.status(400).json({ message: 'Patient not verified First verify Mobile No.' }); } let newPatientData = {}; try { if (req.files) { const patientImage = req.files?.avatar; - const patient = await Patient.findById(req.params?.patientId); + const patient = await Patient.findById(req.patient._id); if (patient?.avatar === null) { // console.log(patient?.avatar) @@ -398,16 +409,10 @@ export const UploadProfileImage = async (req, res) => { url: myCloud.secure_url, }; let patientDetail = await Patient.findByIdAndUpdate( - req.params?.patientId, newPatientData, + req.patient._id, newPatientData, { new: true } // Return the updated document ); - // console.log(patientDetail) - // const patientDetail = await Patient.findByIdAndUpdate(patientId, newPatientData, { - // new: true, - // runValidators: true, - // useFindAndModify: false, - // }); return res.status(200).json({ success: true, @@ -416,16 +421,54 @@ export const UploadProfileImage = async (req, res) => { }); } } catch (error) { - - return res - .status(500) - .json({ message: "Something went wrong!", error: error?.message || "" }); + return res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went wrong!", + }); } }; +export const deletePatient = async (req, res) => { + try { + if (!req.params.id) { + return res.status(400).json({ + success: false, + message: "Please Provide Patient ID!", + }); + } + const getPatient = await Patient.findById(req.params.id); + if (!getPatient) { + return res.status(404).json({ + success: false, + message: "patient not Found!", + }); + } + + // Deleting Images From Cloudinary + if (getPatient?.avatar?.public_id) { + await cloudinary.v2.uploader.destroy(getPatient.avatar?.public_id); + } + + //-------------------------// + const patient = await Patient.findByIdAndDelete(req.params.id); + if (!patient) { + return res.status(404).json({ message: "patient Not Found" }); + } + await patient.remove(); + res.status(200).json({ + success: true, + message: "patient Deleted Successfully!!", + }); + } catch (error) { + res.status(500).json({ + success: false, + message: error.message ? error.message : "Something went wrong!", + }); + } +}; export const completeRegistration = async (req, res) => { diff --git a/resources/Patients/PatientRoute.js b/resources/Patients/PatientRoute.js index e928aba..5a3efa9 100644 --- a/resources/Patients/PatientRoute.js +++ b/resources/Patients/PatientRoute.js @@ -1,8 +1,9 @@ import express from "express"; const router = express.Router(); -// import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js"; -import { EnterPatientDetails, EnterPersonalDetails, Otp, UploadProfileImage, completeRegistration, create1RegistrationDetails, forgotPassword, getAllPatient, loginPatient, register, verifyOtp } from "./PatientController.js"; +import { EnterPatientDetails, EnterPersonalDetails, Otp, UploadProfileImage, completeRegistration, create1RegistrationDetails, deletePatient, forgotPassword, getAllPatient, loginPatient, register, verifyOtp } from "./PatientController.js"; +import { isAuthenticatedPatient } from "../../middlewares/PatientAuth.js"; +import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js"; router.post('/register', register); @@ -10,16 +11,20 @@ router.post('/verify-otp', verifyOtp); router.post('/login', loginPatient); -router.post('/rgstr_details-p1', create1RegistrationDetails); -router.post('/rgstr_details-p2', EnterPatientDetails); -router.post('/rgstr_psrnl_details-p3', EnterPersonalDetails); +router.post('/rgstr_details-p1', isAuthenticatedPatient, create1RegistrationDetails); +router.post('/rgstr_details-p2', isAuthenticatedPatient, EnterPatientDetails); +router.post('/rgstr_psrnl_details-p3', isAuthenticatedPatient, EnterPersonalDetails); -router.get('/getAll', getAllPatient); +router.get('/getAll', isAuthenticatedUser, authorizeRoles("admin"), getAllPatient); router.post('/complete-registration', completeRegistration); router.post('/forgot-password', forgotPassword); -router.post('/upload-image/:patientId', UploadProfileImage); +router.post('/profile-image/upload', isAuthenticatedPatient, UploadProfileImage); +//delete Patient +router.delete('/delete/:id', isAuthenticatedUser, authorizeRoles("admin"), deletePatient); + +