ashok 2 months ago
commit 52d6f39c6f

@ -282,6 +282,52 @@ exports.addUser = async (req, reply) => {
// Accepts a user , password , and checks in the system to see if user exists , and password is valid // Accepts a user , password , and checks in the system to see if user exists , and password is valid
// returns a user object so that jwt token can be created and sent back to the client // returns a user object so that jwt token can be created and sent back to the client
// exports.loginUser = async (req, fcmIds, deviceId) => {
// try {
// const { phone, password } = req.body;
// let user = await User.findOne({ phone });
// let isStaff = false;
// let staffMember = null;
// // If not a main user, check staff inside all users
// if (!user) {
// const users = await User.find({ "staff.staff.phone": phone });
// for (const u of users) {
// const foundStaff = u.staff.staff.find((s) => s.phone === phone);
// if (foundStaff) {
// user = u; // Assign user as the main user under which the staff exists
// staffMember = foundStaff;
// isStaff = true;
// break;
// }
// }
// }
// // If no user or staff found, return invalid credentials
// if (!user) return { same: false };
// // Validate password
// let isSame = false;
// if (isStaff) {
// isSame = password === staffMember.password; // Plain text comparison for staff
// } else {
// isSame = await bcrypt.compare(password, user.services.password.bcrypt); // Bcrypt for main users
// }
// if (!isSame) return { same: false };
// // Update deviceId
// user.deviceId = deviceId;
// await user.save();
// return { same: true, user, isStaff, staffMember };
// } catch (err) {
// throw boom.boomify(err);
// }
// };
exports.loginUser = async (req, fcmIds, deviceId) => { exports.loginUser = async (req, fcmIds, deviceId) => {
try { try {
const { phone, password } = req.body; const { phone, password } = req.body;
@ -289,14 +335,12 @@ exports.loginUser = async (req, fcmIds, deviceId) => {
let isStaff = false; let isStaff = false;
let staffMember = null; let staffMember = null;
// If not a main user, check staff inside all users
if (!user) { if (!user) {
const users = await User.find({ "staff.staff.phone": phone }); const users = await User.find({ "staff.staff.phone": phone });
for (const u of users) { for (const u of users) {
const foundStaff = u.staff.staff.find((s) => s.phone === phone); const foundStaff = u.staff.staff.find((s) => s.phone === phone);
if (foundStaff) { if (foundStaff) {
user = u; // Assign user as the main user under which the staff exists user = u;
staffMember = foundStaff; staffMember = foundStaff;
isStaff = true; isStaff = true;
break; break;
@ -304,20 +348,29 @@ exports.loginUser = async (req, fcmIds, deviceId) => {
} }
} }
// If no user or staff found, return invalid credentials
if (!user) return { same: false }; if (!user) return { same: false };
// Validate password
let isSame = false; let isSame = false;
if (isStaff) { if (isStaff) {
isSame = password === staffMember.password; // Plain text comparison for staff isSame = password === staffMember.password;
} else { } else {
isSame = await bcrypt.compare(password, user.services.password.bcrypt); // Bcrypt for main users const otpMatch =
//user.oneTimePasswordSetFlag &&
user.passwordResetCode &&
password === user.passwordResetCode.toString();
if (otpMatch) {
isSame = true;
user.oneTimePasswordSetFlag = false;
user.passwordResetCode = null;
} else {
isSame = await bcrypt.compare(password, user.services.password.bcrypt);
}
} }
if (!isSame) return { same: false }; if (!isSame) return { same: false };
// Update deviceId
user.deviceId = deviceId; user.deviceId = deviceId;
await user.save(); await user.save();
@ -329,6 +382,7 @@ exports.loginUser = async (req, fcmIds, deviceId) => {
exports.loginUserWithOTP = async (req) => { exports.loginUserWithOTP = async (req) => {
try { try {
const phone = req.body.phone; const phone = req.body.phone;
@ -571,15 +625,105 @@ exports.sendSms = async (request, reply) => {
} }
// exports.forgotPassword = async (req, reply) => {
// try {
// // Create a new User object from the request body
// var user = new User(req.body);
// // Check if the request body is URL encoded
// checkFormEncoding = isUserFormUrlEncoded(req);
// if (checkFormEncoding.isUserFormUrlEncoded) {
// // Extract user information from the request body
// usertobeInserted = checkFormEncoding.user;
// user.username = usertobeInserted.username;
// user.firstName = usertobeInserted.firstName;
// user.lastName = usertobeInserted.lastName;
// user.phone = usertobeInserted.phone;
// user.emails = usertobeInserted.emails;
// }
// // Find a user with the given phone number in the database
// userExists = await User.findOne({
// phone: user.phone,
// });
// if (userExists) {
// // Generate a random password reset code
// const code = Math.floor(100000 + Math.random() * 900000);
// // Convert the code to a string and hash it using bcrypt
// codestr = "";
// codestr = code.toString();
// hash = await bcryptPassword(codestr);
// // Update the user's password reset code and password hash in the database
// const filter = {
// phone: userExists.phone,
// };
// const update = {
// $set: {
// passwordResetCode: code,
// "services.password.bcrypt": hash,
// //oneTimePasswordSetFlag: true,
// },
// };
// const doc = await User.updateOne(filter, update);
// // Find the updated user in the database
// updatedUser = await User.findOne({ phone: userExists.phone });
// if (updatedUser.oneTimePasswordSetFlag) {
// // Send an SMS with the password reset code
// const request = {
// body: {
// mobileNumbers: userExists.phone,
// },
// };
// const response = {
// send: (data) => {
// console.log(data); // Optional: Log the response from the SMS provider
// // Send a success response with the password reset code
// req.body.passwordResetCode = code;
// reply.send('{"armintatankdata":{"error":false,"forgotPassword": true}}');
// },
// };
// await exports.sendSms(request, response);
// } else {
// // Send an error response if the password reset code was not set
// error = {
// armintatankdata: {
// error: true,
// code: 10007,
// message: "10007 - Unable to reset password",
// },
// };
// req.body.regError = error;
// reply.send(error);
// }
// } else {
// // Send an error response if no user was found with the given phone number
// error = {
// armintatankdata: {
// error: true,
// code: 10006,
// message: "10006 - Please check the phone number you entered..",
// },
// };
// req.body.regError = error;
// reply.send(error);
// }
// } catch (err) {
// // Handle any errors that occur during the API request
// throw boom.boomify(err);
// }
// };
exports.forgotPassword = async (req, reply) => { exports.forgotPassword = async (req, reply) => {
try { try {
// Create a new User object from the request body
var user = new User(req.body); var user = new User(req.body);
// Check if the request body is URL encoded
checkFormEncoding = isUserFormUrlEncoded(req); checkFormEncoding = isUserFormUrlEncoded(req);
if (checkFormEncoding.isUserFormUrlEncoded) { if (checkFormEncoding.isUserFormUrlEncoded) {
// Extract user information from the request body
usertobeInserted = checkFormEncoding.user; usertobeInserted = checkFormEncoding.user;
user.username = usertobeInserted.username; user.username = usertobeInserted.username;
user.firstName = usertobeInserted.firstName; user.firstName = usertobeInserted.firstName;
@ -588,38 +732,34 @@ exports.forgotPassword = async (req, reply) => {
user.emails = usertobeInserted.emails; user.emails = usertobeInserted.emails;
} }
// Find a user with the given phone number in the database const userExists = await User.findOne({ phone: user.phone });
userExists = await User.findOne({
phone: user.phone, if (!userExists) {
return reply.send({
armintatankdata: {
error: true,
code: 10006,
message: "10006 - Please check the phone number you entered.",
},
}); });
}
if (userExists) { // Generate a random 6-digit code
// Generate a random password reset code
const code = Math.floor(100000 + Math.random() * 900000); const code = Math.floor(100000 + Math.random() * 900000);
// Convert the code to a string and hash it using bcrypt // Store OTP only (not password hash)
codestr = "";
codestr = code.toString();
hash = await bcryptPassword(codestr);
// Update the user's password reset code and password hash in the database
const filter = {
phone: userExists.phone,
};
const update = { const update = {
$set: { $set: {
passwordResetCode: code, passwordResetCode: code,
"services.password.bcrypt": hash,
oneTimePasswordSetFlag: true, oneTimePasswordSetFlag: true,
}, },
}; };
const doc = await User.updateOne(filter, update);
// Find the updated user in the database await User.updateOne({ phone: userExists.phone }, update);
updatedUser = await User.findOne({ phone: userExists.phone });
const updatedUser = await User.findOne({ phone: userExists.phone });
if (updatedUser.oneTimePasswordSetFlag) { if (updatedUser.oneTimePasswordSetFlag) {
// Send an SMS with the password reset code
const request = { const request = {
body: { body: {
mobileNumbers: userExists.phone, mobileNumbers: userExists.phone,
@ -627,45 +767,76 @@ exports.forgotPassword = async (req, reply) => {
}; };
const response = { const response = {
send: (data) => { send: (data) => {
console.log(data); // Optional: Log the response from the SMS provider console.log(data);
// Send a success response with the password reset code
req.body.passwordResetCode = code; req.body.passwordResetCode = code;
reply.send('{"armintatankdata":{"error":false,"forgotPassword": true}}'); reply.send({
armintatankdata: {
error: false,
forgotPassword: true,
},
});
}, },
}; };
await exports.sendSms(request, response); await exports.sendSms(request, response);
} else { } else {
// Send an error response if the password reset code was not set return reply.send({
error = {
armintatankdata: { armintatankdata: {
error: true, error: true,
code: 10007, code: 10007,
message: "10007 - Unable to reset password", message: "Unable to reset password",
},
};
req.body.regError = error;
reply.send(error);
}
} else {
// Send an error response if no user was found with the given phone number
error = {
armintatankdata: {
error: true,
code: 10006,
message: "10006 - Please check the phone number you entered..",
}, },
}; });
req.body.regError = error;
reply.send(error);
} }
} catch (err) { } catch (err) {
// Handle any errors that occur during the API request
throw boom.boomify(err); throw boom.boomify(err);
} }
}; };
// exports.forgotPassword = async (req, reply) => {
// try {
// const user = await User.findOne({ phone: req.body.phone });
// if (!user) {
// return reply.send({
// armintatankdata: {
// error: true,
// code: 10006,
// message: "10006 - Please check the phone number you entered..",
// },
// });
// }
// const code = Math.floor(100000 + Math.random() * 900000).toString();
// const hashedOTP = await bcrypt.hash(code, 10);
// await User.updateOne(
// { phone: user.phone },
// {
// $set: {
// "services.password.bcrypt": hashedOTP,
// temporaryPasswordCode: code,
// oneTimePasswordSetFlag: true,
// },
// }
// );
// // Simulated SMS logic
// console.log("OTP sent:", code);
// reply.send({
// armintatankdata: {
// error: false,
// forgotPassword: true,
// },
// });
// } catch (err) {
// throw boom.boomify(err);
// }
// };
exports.changePassword = async (req, reply) => { exports.changePassword = async (req, reply) => {
try { try {

@ -155,6 +155,123 @@ fastify.register(require('point-of-view'), {
// * This is for login user as a simply user * // * This is for login user as a simply user *
fastify.post("/api/login", {
schema: {
description: "This is for Login User",
tags: ["Login"],
summary: "This is for User Login",
body: {
type: "object",
required: ["phone", "password"],
properties: {
phone: { type: "string" },
password: { type: "string" },
fcmIds: { type: "array", items: { type: "string" }, default: [] },
deviceId: { type: "string" },
},
},
},
async handler(req, reply) {
const { phone, password, fcmIds, deviceId } = req.body;
console.log(password, phone);
const loginObject = await userController.loginUser(req, fcmIds, deviceId);
console.log("loginObject",loginObject)
if (!loginObject.same) {
return reply.send({
simplydata: {
error: true,
code: 400,
message: "Invalid UserId or Password supplied",
},
});
}
const user = loginObject.user;
const phoneVerified = user.phoneVerified;
const oneTimePasswordSetFlag = user.oneTimePasswordSetFlag;
if (fcmIds.length > 0) {
await User.updateOne(
{ customerId: user.customerId },
{ $addToSet: { fcmIds: { $each: fcmIds } } }
);
}
if (!phoneVerified) {
return reply.send({
simplydata: {
error: false,
phoneVerified: false,
phone: loginObject.isStaff ? loginObject.staffMember.phone : user.phone,
oneTimePasswordSetFlag,
message: "Please Verify your phone number",
},
});
}
// if (oneTimePasswordSetFlag) {
// return reply.send({
// simplydata: {
// error: false,
// phoneVerified,
// phone: loginObject.isStaff ? loginObject.staffMember.phone : user.phone,
// oneTimePasswordSetFlag: true,
// message: "Password must be reset",
// },
// });
// }
const tokenPayload = {
username: loginObject.isStaff ? loginObject.staffMember.name : user.username,
userId: user._id,
roles: user.profile.role,
};
const token = fastify.jwt.sign(tokenPayload, { expiresIn: "30d" });
const profilePicture = await ProfilePicture.findOne({ customerId: user.customerId });
const responsePayload = {
simplydata: {
error: false,
apiversion: fastify.config.APIVERSION,
access_token: token,
buildingName: user.buildingName,
email: user.emails,
phone: loginObject.isStaff ? loginObject.staffMember.phone : user.phone,
customerId: user.customerId,
username: loginObject.isStaff ? loginObject.staffMember.name : user.username,
address1: user.profile.address1,
address2: user.profile.address2,
phoneVerified: user.phoneVerified,
oneTimePasswordSetFlag: user.oneTimePasswordSetFlag,
latitude: user.latitude,
longitude: user.longitude,
type: user.profile.role,
loginType: loginObject.isStaff ? "staff" : "user",
},
};
if (loginObject.isStaff) {
let allMotorAccess = loginObject.staffMember.all_motor_access;
// Normalize the value if it matches the given variations
if (["view", "view only", "View", "View Only"].includes(allMotorAccess)) {
allMotorAccess = "view";
}
responsePayload.simplydata.all_motor_access = allMotorAccess;
}
if (profilePicture) {
responsePayload.simplydata.picture = profilePicture.picture;
}
reply.send(responsePayload);
},
});
// fastify.post("/api/login", { // fastify.post("/api/login", {
// schema: { // schema: {
// description: "This is for Login User", // description: "This is for Login User",
@ -164,33 +281,31 @@ fastify.register(require('point-of-view'), {
// type: "object", // type: "object",
// required: ["phone", "password"], // required: ["phone", "password"],
// properties: { // properties: {
// phone: { type: "string" }, // phone: { type: "string", description: "Registered phone number" },
// password: { type: "string" }, // password: { type: "string", description: "Password for authentication" },
// fcmIds: { type: "array", items: { type: "string" }, default: [] }, // fcmIds: { type: "array", items: { type: "string" }, default: [] },
// deviceId: { type: "string" }, // deviceId: { type: "string" }
// }, // }
// }, // }
// }, // },
// async handler(req, reply) { // async handler(req, reply) {
// const { phone, password, fcmIds, deviceId } = req.body; // try {
// console.log(password, phone); // const { phone, password, fcmIds = [], deviceId } = req.body;
// const loginObject = await userController.loginUser(req, fcmIds, deviceId); // // Find user by phone
// console.log("loginObject",loginObject) // const user = await User.findOne({ phone });
// if (!loginObject.same) { // console.log("user",user)
// return reply.send({ // if (!user) {
// simplydata: { // return reply.code(400).send({ simplydata: { error: true, message: "User not found" } });
// error: true,
// code: 400,
// message: "Invalid UserId or Password supplied",
// },
// });
// } // }
// const user = loginObject.user; // // Verify password (bcrypt)
// const phoneVerified = user.phoneVerified; // const isMatch = await bcrypt.compare(password, user.services.password.bcrypt);
// const oneTimePasswordSetFlag = user.oneTimePasswordSetFlag; // if (!isMatch) {
// return reply.code(400).send({ simplydata: { error: true, message: "Invalid credentials" } });
// }
// // Update FCM Ids if present
// if (fcmIds.length > 0) { // if (fcmIds.length > 0) {
// await User.updateOne( // await User.updateOne(
// { customerId: user.customerId }, // { customerId: user.customerId },
@ -198,49 +313,57 @@ fastify.register(require('point-of-view'), {
// ); // );
// } // }
// if (!phoneVerified) { // // Phone Verification
// if (!user.phoneVerified) {
// return reply.send({ // return reply.send({
// simplydata: { // simplydata: {
// error: false, // error: false,
// phoneVerified: false, // phoneVerified: false,
// phone: loginObject.isStaff ? loginObject.staffMember.phone : user.phone, // phone: user.phone,
// oneTimePasswordSetFlag, // oneTimePasswordSetFlag: user.oneTimePasswordSetFlag,
// message: "Please Verify your phone number", // message: "Please Verify your phone number"
// }, // }
// }); // });
// } // }
// if (oneTimePasswordSetFlag) { // // Password reset flag
// if (user.oneTimePasswordSetFlag) {
// return reply.send({ // return reply.send({
// simplydata: { // simplydata: {
// error: false, // error: false,
// phoneVerified, // phoneVerified: user.phoneVerified,
// phone: loginObject.isStaff ? loginObject.staffMember.phone : user.phone, // phone: user.phone,
// oneTimePasswordSetFlag: true, // oneTimePasswordSetFlag: true,
// message: "Password must be reset", // message: "Password must be reset"
// }, // }
// }); // });
// } // }
// // JWT Token Payload
// const tokenPayload = { // const tokenPayload = {
// username: loginObject.isStaff ? loginObject.staffMember.name : user.username, // username: user.username,
// userId: user._id, // userId: user._id,
// roles: user.profile.role, // roles: user.profile.role
// }; // };
// const token = fastify.jwt.sign(tokenPayload, { expiresIn: "30d" }); // // JWT Token Generation (matches /api/storelogin style)
// const token = fastify.jwt.sign(tokenPayload, /* no direct secret here, assumes plugin config */{ expiresIn: "30d" });
// // Profile Picture
// const profilePicture = await ProfilePicture.findOne({ customerId: user.customerId }); // const profilePicture = await ProfilePicture.findOne({ customerId: user.customerId });
// // Response Construction
// const responsePayload = { // const responsePayload = {
// simplydata: { // simplydata: {
// error: false, // error: false,
// apiversion: fastify.config.APIVERSION, // message: "Login successful",
// apiversion: fastify.config ? fastify.config.APIVERSION : undefined,
// access_token: token, // access_token: token,
// buildingName: user.buildingName, // buildingName: user.buildingName,
// email: user.emails, // email: user.emails,
// phone: loginObject.isStaff ? loginObject.staffMember.phone : user.phone, // phone: user.phone,
// customerId: user.customerId, // customerId: user.customerId,
// username: loginObject.isStaff ? loginObject.staffMember.name : user.username, // username: user.username,
// address1: user.profile.address1, // address1: user.profile.address1,
// address2: user.profile.address2, // address2: user.profile.address2,
// phoneVerified: user.phoneVerified, // phoneVerified: user.phoneVerified,
@ -248,145 +371,22 @@ fastify.register(require('point-of-view'), {
// latitude: user.latitude, // latitude: user.latitude,
// longitude: user.longitude, // longitude: user.longitude,
// type: user.profile.role, // type: user.profile.role,
// loginType: loginObject.isStaff ? "staff" : "user", // loginType: "user"
// },
// };
// if (loginObject.isStaff) {
// let allMotorAccess = loginObject.staffMember.all_motor_access;
// // Normalize the value if it matches the given variations
// if (["view", "view only", "View", "View Only"].includes(allMotorAccess)) {
// allMotorAccess = "view";
// }
// responsePayload.simplydata.all_motor_access = allMotorAccess;
// } // }
// };
// if (profilePicture) { // if (profilePicture) {
// responsePayload.simplydata.picture = profilePicture.picture; // responsePayload.simplydata.picture = profilePicture.picture;
// } // }
// reply.send(responsePayload); // return reply.send(responsePayload);
// },
// });
fastify.post("/api/login", {
schema: {
description: "This is for Login User",
tags: ["Login"],
summary: "This is for User Login",
body: {
type: "object",
required: ["phone", "password"],
properties: {
phone: { type: "string", description: "Registered phone number" },
password: { type: "string", description: "Password for authentication" },
fcmIds: { type: "array", items: { type: "string" }, default: [] },
deviceId: { type: "string" }
}
}
},
async handler(req, reply) {
try {
const { phone, password, fcmIds = [], deviceId } = req.body;
// Find user by phone
const user = await User.findOne({ phone });
console.log("user",user)
if (!user) {
return reply.code(400).send({ simplydata: { error: true, message: "User not found" } });
}
// Verify password (bcrypt)
const isMatch = await bcrypt.compare(password, user.services.password.bcrypt);
if (!isMatch) {
return reply.code(400).send({ simplydata: { error: true, message: "Invalid credentials" } });
}
// Update FCM Ids if present
if (fcmIds.length > 0) {
await User.updateOne(
{ customerId: user.customerId },
{ $addToSet: { fcmIds: { $each: fcmIds } } }
);
}
// Phone Verification
if (!user.phoneVerified) {
return reply.send({
simplydata: {
error: false,
phoneVerified: false,
phone: user.phone,
oneTimePasswordSetFlag: user.oneTimePasswordSetFlag,
message: "Please Verify your phone number"
}
});
}
// Password reset flag
if (user.oneTimePasswordSetFlag) {
return reply.send({
simplydata: {
error: false,
phoneVerified: user.phoneVerified,
phone: user.phone,
oneTimePasswordSetFlag: true,
message: "Password must be reset"
}
});
}
// JWT Token Payload
const tokenPayload = {
username: user.username,
userId: user._id,
roles: user.profile.role
};
// JWT Token Generation (matches /api/storelogin style)
const token = fastify.jwt.sign(tokenPayload, /* no direct secret here, assumes plugin config */{ expiresIn: "30d" });
// Profile Picture
const profilePicture = await ProfilePicture.findOne({ customerId: user.customerId });
// Response Construction
const responsePayload = {
simplydata: {
error: false,
message: "Login successful",
apiversion: fastify.config ? fastify.config.APIVERSION : undefined,
access_token: token,
buildingName: user.buildingName,
email: user.emails,
phone: user.phone,
customerId: user.customerId,
username: user.username,
address1: user.profile.address1,
address2: user.profile.address2,
phoneVerified: user.phoneVerified,
oneTimePasswordSetFlag: user.oneTimePasswordSetFlag,
latitude: user.latitude,
longitude: user.longitude,
type: user.profile.role,
loginType: "user"
}
};
if (profilePicture) {
responsePayload.simplydata.picture = profilePicture.picture;
}
return reply.send(responsePayload);
} catch (error) { // } catch (error) {
console.error("Login Error:", error); // console.error("Login Error:", error);
return reply.code(500).send({ simplydata: { error: true, message: "Internal server error" } }); // return reply.code(500).send({ simplydata: { error: true, message: "Internal server error" } });
} // }
} // }
}); // });

Loading…
Cancel
Save