change mobile number Update Profile get Profile etc

This commit is contained in:
pawan-dot 2024-07-05 14:34:16 +05:30
parent bb556746ec
commit edb977c601
4 changed files with 198 additions and 44 deletions

View File

@ -31,10 +31,21 @@ export const isAuthenticatedPatient = async (req, res, next) => {
}); });
} }
} catch (error) { } catch (error) {
return res.status(401).json({ if (error.name === 'TokenExpiredError') {
success: false, return res.status(401).json({ message: 'Token has expired.' });
message: error.message, } else if (error.name === 'JsonWebTokenError') {
}); if (error.message === 'invalid signature') {
return res.status(401).json({ message: 'Invalid token!.' });
} else {
return res.status(401).json({ message: 'Invalid token.' });
}
} else {
return res.status(500).json({ message: 'An internal error occurred while verifying the token.' });
}
// return res.status(401).json({
// success: false,
// message: error.message,
// });
} }
}; };

View File

@ -10,8 +10,8 @@ import cloudinary from '../../Utils/cloudinary.js';
export const register = async (req, res) => { export const register = async (req, res) => {
let { name, countryCode, mobileNumber } = req.body; let { name, countryCode, mobileNumber } = req.body;
// Trim the country code and mobile number // Trim the country code and mobile number
countryCode = countryCode.trim(); countryCode = countryCode?.trim();
mobileNumber = mobileNumber.trim(); mobileNumber = mobileNumber?.trim();
const fullMobileNumber = `${countryCode}${mobileNumber}`; const fullMobileNumber = `${countryCode}${mobileNumber}`;
try { try {
let patient = await Patient.findOne({ mobileNumber: fullMobileNumber }); let patient = await Patient.findOne({ mobileNumber: fullMobileNumber });
@ -43,7 +43,7 @@ export const register = async (req, res) => {
export const verifyOtp = async (req, res) => { export const verifyOtp = async (req, res) => {
const { mobileNumber, otp } = req.body; const { mobileNumber, otp } = req.body;
try { try {
let mobileNmr = mobileNumber.trim(); let mobileNmr = mobileNumber?.trim();
const patient = await Patient.findOne({ mobileNumber: mobileNmr }); const patient = await Patient.findOne({ mobileNumber: mobileNmr });
if (!patient) { if (!patient) {
@ -391,10 +391,8 @@ export const UploadProfileImage = async (req, res) => {
const patientImage = req.files?.avatar; const patientImage = req.files?.avatar;
const patient = await Patient.findById(req.patient._id); const patient = await Patient.findById(req.patient._id);
if (patient?.avatar === null) { if (patient?.avatar?.public_id) {
// console.log(patient?.avatar)
const imageId = patient?.avatar?.public_id; const imageId = patient?.avatar?.public_id;
await cloudinary.uploader.destroy(imageId) await cloudinary.uploader.destroy(imageId)
} }
@ -430,7 +428,97 @@ export const UploadProfileImage = async (req, res) => {
}; };
//Update mobile Number
export const updateMobileNumber = async (req, res) => {
let { newCountryCode, newMobileNumber } = req.body;
newCountryCode = newCountryCode?.trim();
newMobileNumber = newMobileNumber?.trim();
const newFullMobileNumber = `${newCountryCode}${newMobileNumber}`;
try {
if (req.patient?.mobileNumber === newFullMobileNumber) {
return res.status(400).json({ message: 'New mobile number cannot be the same as the old mobile number' });
}
let patient = await Patient.findOne({ mobileNumber: req.patient?.mobileNumber });
if (!patient) {
return res.status(400).json({ message: 'Patient not found' });
}
const otp = crypto.randomInt(100000, 1000000).toString();
const otpExpires = Date.now() + 3 * 60 * 1000; // 3 minutes
patient.newMobileNumber = newFullMobileNumber;
patient.otp = otp;
patient.otpExpires = otpExpires;
await patient.save();
await sendOtp(newFullMobileNumber, `Your tavisa verification OTP is: ${otp}`);
return res.status(200).json({ message: `OTP sent to your new mobile number ${newFullMobileNumber} successfully` });
} catch (error) {
res.status(500).json({
message: error.message ? error.message : "Server error!",
});
}
};
//verify Updated Number OTP
export const verifyUpdatedMobileOtp = async (req, res) => {
const { newMobileNumber, otp } = req.body;
try {
let mobileNmr = newMobileNumber?.trim();
const patient = await Patient.findOne({ newMobileNumber: mobileNmr });
if (!patient) {
return res.status(400).json({ message: 'Invalid mobile number or OTP' });
}
if (patient.otp !== otp || patient.otpExpires < Date.now()) {
return res.status(400).json({ message: 'Invalid or expired OTP' });
}
patient.mobileNumber = patient.newMobileNumber;
patient.newMobileNumber = undefined;
patient.isVerified = true;
patient.otp = undefined;
patient.otpExpires = undefined;
await patient.save();
const token = patient.getJWTToken();
res.status(200).json({
success: true,
token, message: 'Mobile number updated and verified successfully'
});
} catch (error) {
res.status(500).json({
message: error.message ? error.message : "Server error!",
});
}
};
//getmyProfile
export const getmyProfile = async (req, res) => {
try {
const myData = await Patient.findById(req.patient?._id);
if (myData) {
return res.status(200).json({
success: true,
message: "feched!",
myData,
});
}
} catch (error) {
return res.status(500).json({
success: false,
message: error.message ? error.message : "Something went wrong!",
});
}
}
//
export const deletePatient = async (req, res) => { export const deletePatient = async (req, res) => {
try { try {
if (!req.params.id) { if (!req.params.id) {
@ -471,55 +559,104 @@ export const deletePatient = async (req, res) => {
}; };
export const completeRegistration = async (req, res) => { export const UpdateProile = async (req, res) => {
const { const {
mobileNumber, name,
email, email,
password,
confirmPassword,
gender, gender,
weight, weightValue,
height, weightUnit,
heightValue,
heightUnit,
age, age,
commonHealthComplaints, commonHealthComplaints,
familyHistory, familyHistory,
personalHistory, personalHistory,
dailyRoutine, dailyRoutine,
} = req.body; } = req.body;
if (password !== confirmPassword) { // Validate email
return res.status(400).json({ message: 'Password and confirm password do not match' }); if (email && !validator.isEmail(email)) {
return res.status(400).json({ message: 'Invalid email address' });
} }
try {
const patient = await Patient.findOne({ mobileNumber });
if (!patient || !patient.isVerified) { //gender Validate
return res.status(400).json({ message: 'Patient not found or not verified' }); if (gender && !['Male', 'Female'].includes(gender)) {
return res.status(400).json({ message: 'Invalid gender:gender Must be "Male" or "Female"' });
}
// Validate weightUnit
if (weightUnit && !['Kgs', 'Lbs'].includes(weightUnit)) {
return res.status(400).json({ message: 'Invalid weight unit. Must be "Kgs" or "Lbs"' });
}
// Ensure weightValue is a number
if (weightValue && isNaN(weightValue)) {
return res.status(400).json({ message: 'Weight value must be a number' });
}
// Validate heightUnit
if (heightUnit && !['Ft', 'Cm'].includes(heightUnit)) {
return res.status(400).json({ message: 'Invalid height unit. Must be "Ft" or "Cm"' });
}
// Ensure heightValue is a number
if (heightValue && isNaN(heightValue)) {
return res.status(400).json({ message: 'Height value must be a number' });
}
if (age && isNaN(age)) {
return res.status(400).json({ message: 'age must be a number' });
}
try {
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' });
}
if (email) {
const emailExists = await Patient.findOne({ email });
if (emailExists && emailExists._id.toString() !== req.patient._id) {
return res.status(400).json({ message: 'This Email ID is already in use By Another patient' });
}
} }
// const hashedPassword = await hashPassword(password); const updateData = {
weight: {
patient.email = email; value: weightValue,
patient.password = hashedPassword; unit: weightUnit,
patient.gender = gender; },
patient.weight = weight; height: {
patient.height = height; value: heightValue,
patient.age = age; unit: heightUnit,
patient.commonHealthComplaints = commonHealthComplaints; },
patient.familyHistory = familyHistory; ...req.body
patient.personalHistory = personalHistory; };
patient.dailyRoutine = dailyRoutine; let NewPatientDetail = await Patient.findByIdAndUpdate(
req.patient._id,
await patient.save(); updateData
,
res.status(200).json({ message: 'Registration details updated successfully' }); { new: true } // Return the updated document
);
// patient.gender = gender;
// patient.weight = {
// value: weightValue,
// unit: weightUnit,
// };
// patient.height = {
// value: heightValue,
// unit: heightUnit,
// };
// patient.age = age;
// await patient.save();
// const patientResponse = patient.toObject();
// delete patientResponse.password;
return res.status(200).json({ patient: NewPatientDetail, message: 'Profile updated successfully' });
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: error.message ? error.message : "Server error!", message: error.message ? error.message : "Server error!",
}); });
} }
}; }
export const Otp = async (req, res) => { export const Otp = async (req, res) => {

View File

@ -82,7 +82,7 @@ const patientSchema = new mongoose.Schema(
familyHistory: String, familyHistory: String,
personalHistory: String, personalHistory: String,
dailyRoutine: String, dailyRoutine: String,
newMobileNumber: { type: String },
resetPasswordToken: String, resetPasswordToken: String,
resetPasswordExpire: Date, resetPasswordExpire: Date,
}, },

View File

@ -1,7 +1,7 @@
import express from "express"; import express from "express";
const router = express.Router(); const router = express.Router();
import { EnterPatientDetails, EnterPersonalDetails, Otp, UploadProfileImage, completeRegistration, create1RegistrationDetails, deletePatient, forgotPassword, getAllPatient, loginPatient, register, verifyOtp } from "./PatientController.js"; import { EnterPatientDetails, EnterPersonalDetails, Otp, UploadProfileImage, create1RegistrationDetails, deletePatient, forgotPassword, getAllPatient, loginPatient, register, updateMobileNumber, verifyUpdatedMobileOtp, verifyOtp, UpdateProile, getmyProfile } from "./PatientController.js";
import { isAuthenticatedPatient } from "../../middlewares/PatientAuth.js"; import { isAuthenticatedPatient } from "../../middlewares/PatientAuth.js";
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js"; import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
@ -16,11 +16,17 @@ router.post('/rgstr_details-p2', isAuthenticatedPatient, EnterPatientDetails);
router.post('/rgstr_psrnl_details-p3', isAuthenticatedPatient, EnterPersonalDetails); router.post('/rgstr_psrnl_details-p3', isAuthenticatedPatient, EnterPersonalDetails);
router.get('/getAll', isAuthenticatedUser, authorizeRoles("admin"), getAllPatient); router.get('/getAll', isAuthenticatedUser, authorizeRoles("admin"), getAllPatient);
router.get('/my-profile', isAuthenticatedPatient, getmyProfile);
router.post('/complete-registration', completeRegistration); //Update Mobile Number
router.post('/update-mobile-number', isAuthenticatedPatient, updateMobileNumber);
router.post('/verify-updated-mobile-otp', isAuthenticatedPatient, verifyUpdatedMobileOtp);
router.post('/forgot-password', forgotPassword); router.post('/forgot-password', forgotPassword);
router.post('/profile-image/upload', isAuthenticatedPatient, UploadProfileImage); router.post('/profile-image/upload', isAuthenticatedPatient, UploadProfileImage);
router.patch('/profile/update', isAuthenticatedPatient, UpdateProile);
//delete Patient //delete Patient
router.delete('/delete/:id', isAuthenticatedUser, authorizeRoles("admin"), deletePatient); router.delete('/delete/:id', isAuthenticatedUser, authorizeRoles("admin"), deletePatient);