From 143063557f4234206619e12e795c3eec0dd021e0 Mon Sep 17 00:00:00 2001 From: Naidu Date: Thu, 27 Jun 2024 14:40:58 +0530 Subject: [PATCH 01/11] Store Signup and login --- src/controllers/storeController.js | 71 ++++++++++++++++++++++++++++++ src/index.js | 3 ++ src/models/store.js | 55 +++++++++++++++++++++++ src/routes/storeRoute.js | 63 ++++++++++++++++++++++++++ 4 files changed, 192 insertions(+) create mode 100644 src/controllers/storeController.js create mode 100644 src/models/store.js create mode 100644 src/routes/storeRoute.js diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js new file mode 100644 index 00000000..bbaac118 --- /dev/null +++ b/src/controllers/storeController.js @@ -0,0 +1,71 @@ +const boom = require("boom"); +const jwt = require('jsonwebtoken') +const bcrypt = require('bcrypt') + +const fastify = require("fastify"); +const { Store } = require("../models/store"); + +exports.storeSignUp = async (request, reply) => { + + try { + const { phone1,name,phone2, city,team,manager,picture,email, password } = request.body + + // Check if the email address is valid + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ + if (!emailRegex.test(email)) { + return reply.status(400).send({ message: 'Invalid email address' }) + } + + // Check if an admin with the same email address already exists + const existingstore = await Store.findOne({ phone1 }) + + if (existingstore) { + return reply.status(400).send({ message: 'Phone is already registered' }) + } + + // Hash the password using bcrypt + const hashedPassword = await bcrypt.hash(password, 10) + + // Create a new admin object with the hashed password + const store = new Store({ phone1,name,phone2, city,team,manager,picture,email, password: hashedPassword }) + + // Save the new admin to the database + await store.save() + + + reply.send({message : "Store Account Created Sucessfully"}) + } catch (err) { + reply.status(500).send({ message: err.message }) + } + } + + + + exports.storeLogin = async (request, reply) => { + try { + const { phone1, password } = request.body + + // Check if an admin with the email address exists + const store = await Store.findOne({ phone1 }) + + if (!store) { + return reply.status(401).send({ message: 'Invalid Phone1 or password' }) + } + + // Compare the password entered by the user with the hashed password stored in the database + const isPasswordValid = await bcrypt.compare(password, store.password) + + if (!isPasswordValid) { + return reply.status(401).send({ message: 'Invalid phone or password' }) + } + + // Generate a JWT token for the authenticated admin + const token = jwt.sign({ phone1: store.phone1 }, 'secret') + + // Return the token to the client + return { token } + } catch (err) { + reply.status(500).send({ message: err.message }) + } + } + diff --git a/src/index.js b/src/index.js index e9df1586..e08cba81 100644 --- a/src/index.js +++ b/src/index.js @@ -4,6 +4,8 @@ const { User,Counter, generateBookingId,resetCounter,generateCustomerId,ProfileP //const tanksController = require("./controllers/tanksController"); const tankersController = require("./controllers/tankersController.js"); const createConnectionController = require("./controllers/createConnectionController"); +const storeController = require("./controllers/storeController.js") + const cors = require("cors"); const swagger = require("./config/swagger"); const rawBody = require('raw-body') @@ -346,6 +348,7 @@ fastify.register(require("./routes/supplierRoute")); fastify.register(require("./routes/supplierOrdersRoutes")); fastify.register(require("./routes/friendRequestRoute")); fastify.register(require("./routes/adminRoute")); +fastify.register(require("./routes/storeRoute")); // Testing route allows for retrieving a user by phone so one can see what is the phone verification code sent for a given user's phone // Also allows deletion of a user with a given phone number diff --git a/src/models/store.js b/src/models/store.js new file mode 100644 index 00000000..24eabcc7 --- /dev/null +++ b/src/models/store.js @@ -0,0 +1,55 @@ +const mongoose = require('mongoose') +const Schema = mongoose.Schema; +const ObjectId = Schema.Types.ObjectId; + + + +const storeschema = new mongoose.Schema({ + name: { + type: String, + required: true, + + }, + email: { + type: String, + required: true, + unique: true, + lowercase: true + }, + + phone1: { + type: String, + default: false, + + }, + phone2: { + type: String, + default: false, + + }, + city: { + type: String, + required: true, + }, + team:{ + type:String + + }, + location: { + type:String, + default: false, + }, + picture: + { type: String }, + manager:{ + type: String, + default:false, + }, + password: + { type: String}, + + }); + + const Store = mongoose.model("Store", storeschema); + + module.exports = { Store}; diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js new file mode 100644 index 00000000..4935bcc5 --- /dev/null +++ b/src/routes/storeRoute.js @@ -0,0 +1,63 @@ +const fastify = require("fastify"); +const storeController = require('../controllers/storeController') + + +module.exports = function (fastify, opts, next) { +fastify.route({ + method: "POST", + url: "/api/storeSignup", + schema: { + tags: ["Store"], + description: "This is for cretae New Store Account", + summary: "This is for cretae New Store Account", + body: { + type: "object", + properties: { + name:{ type: "string"}, + phone1: { type: "string"}, + phone2: { type: "string"}, + city: { type: "string"}, + location: { type: "string"}, + picture: { type: "string"}, + team: { type: "string"}, + manager: { type: "string"}, + + email: { type: "string" }, + password: { type: "string" }, + + }, + }, + security: [ + { + basicAuth: [], + }, + ], + }, + + handler: storeController.storeSignUp, + + }); + + fastify.post("/api/storeLogin", { + schema: { + description: "This is for Login Store", + tags: ["Store"], + summary: "This is for Login Store", + body: { + type: "object", + required: ["phone1", "password"], + properties: { + phone1: { type: "string" }, + password: { type: "string" }, + }, + }, + }, + handler: storeController.storeLogin, +}); + + + + + +next(); +}; From 03953a5aed6077bccead780d0679922a61c7af61 Mon Sep 17 00:00:00 2001 From: Naidu Date: Fri, 28 Jun 2024 11:22:11 +0530 Subject: [PATCH 02/11] singup & login with OTP Installation App --- src/controllers/storeController.js | 259 ++++++++++++++++++++++++----- src/controllers/userController.js | 40 +++++ src/index.js | 102 ++++++++++++ src/models/store.js | 104 +++++++----- src/routes/storeRoute.js | 107 +++++++----- 5 files changed, 491 insertions(+), 121 deletions(-) diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index bbaac118..dc224f07 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -1,66 +1,98 @@ const boom = require("boom"); -const jwt = require('jsonwebtoken') -const bcrypt = require('bcrypt') +const bcrypt = require('bcrypt'); +const jwt = require('jsonwebtoken'); const fastify = require("fastify"); -const { Store } = require("../models/store"); +const { Install, ProfilePictureInstall } = require("../models/store"); -exports.storeSignUp = async (request, reply) => { +const supplierController = require("../controllers/supplierController") - try { - const { phone1,name,phone2, city,team,manager,picture,email, password } = request.body - - // Check if the email address is valid - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ - if (!emailRegex.test(email)) { - return reply.status(400).send({ message: 'Invalid email address' }) - } - - // Check if an admin with the same email address already exists - const existingstore = await Store.findOne({ phone1 }) - - if (existingstore) { - return reply.status(400).send({ message: 'Phone is already registered' }) - } - - // Hash the password using bcrypt - const hashedPassword = await bcrypt.hash(password, 10) - - // Create a new admin object with the hashed password - const store = new Store({ phone1,name,phone2, city,team,manager,picture,email, password: hashedPassword }) - - // Save the new admin to the database - await store.save() - - reply.send({message : "Store Account Created Sucessfully"}) - } catch (err) { - reply.status(500).send({ message: err.message }) + + +exports.installSignUp = async (request, reply) => { + try { + const { + name, + phone, + address, + installationId, + emails, + password, + profile, + team, + manager, + longitude, + latitude, + fcmId, + createdBy, + updatedBy, + } = request.body; + + // Check if the email address is valid + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (emails.some((emailObj) => !emailRegex.test(emailObj.email))) { + return reply.status(400).send({ message: 'Invalid email address' }); } - } + + // Check if a user with the same phone number already exists + const existingInstall = await Install.findOne({ phone }); + if (existingInstall) { + return reply.status(400).send({ message: 'Phone is already registered' }); + } + + // Hash the password using bcrypt + const hashedPassword = await bcrypt.hash(password, 10); + + // Create a new install object with the hashed password and other details + const install = new Install({ + name, + phone, + address, + installationId, + emails, + services: { password: { bcrypt: hashedPassword } }, + profile, + team, + manager, + longitude, + latitude, + fcmId, + createdBy, + updatedBy, + }); + + // Save the new install to the database + await install.save(); + + reply.send({ message: 'Install Account Created Successfully' }); + } catch (err) { + reply.status(500).send({ message: err.message }); + } + }; - exports.storeLogin = async (request, reply) => { + exports.installLogin = async (request, reply) => { try { const { phone1, password } = request.body // Check if an admin with the email address exists - const store = await Store.findOne({ phone1 }) + const install = await Install.findOne({ phone1 }) - if (!store) { + if (!install) { return reply.status(401).send({ message: 'Invalid Phone1 or password' }) } // Compare the password entered by the user with the hashed password stored in the database - const isPasswordValid = await bcrypt.compare(password, store.password) + const isPasswordValid = await bcrypt.compare(password, install.password) if (!isPasswordValid) { return reply.status(401).send({ message: 'Invalid phone or password' }) } // Generate a JWT token for the authenticated admin - const token = jwt.sign({ phone1: store.phone1 }, 'secret') + const token = jwt.sign({ phone1: install.phone1 }, 'secret') // Return the token to the client return { token } @@ -69,3 +101,154 @@ exports.storeSignUp = async (request, reply) => { } } + + + exports.installationVerifyPhone = async (req, reply) => { + console.log("-------------------------------------------------"); + try { + phone = req.body.phone; + phoneVerificationCode = req.body.phoneVerificationCode; + + // check if user exists in the system. If user exists , display message that + // username is not available + console.log( + "this is the phone and verification code", + phone, + phoneVerificationCode + ); + deliveryBoyExists = await Install.findOne({ + phone: phone, + //phoneVerified: false, + phoneVerificationCode: phoneVerificationCode, + }); + console.log(deliveryBoyExists); + if (deliveryBoyExists) { + // update the phoneVerified flag to true. + const filter = { + phone: phone, + phoneVerificationCode: phoneVerificationCode, + }; + const update = { phoneVerified: true }; + const doc = await Install.findOneAndUpdate(filter, update); + updatedDeliveryBoy = await Install.findOne({ phone: phone }); + + if (updatedDeliveryBoy.phoneVerified) { + loginObject = await supplierController.loginInstallation(req); + console.log("loginObject...", loginObject); + if (loginObject.same) { + const phoneVerified = loginObject.delivery.phoneVerified; + const oneTimePasswordSetFlag = + loginObject.delivery.oneTimePasswordSetFlag; + console.log( + "oneTimePasswordSetFlag is ......", + oneTimePasswordSetFlag, + typeof oneTimePasswordSetFlag, + typeof phoneVerified + ); + if (!phoneVerified) { + reply.send({ + simplydata: { + error: false, + phoneVerified: false, + + phone: loginObject.delivery.phone, + oneTimePasswordSetFlag: oneTimePasswordSetFlag, + message: "Please Verify your phone number", + }, + }); + } else if (oneTimePasswordSetFlag) { + reply.send({ + simplydata: { + error: false, + phoneVerified: phoneVerified, + phone: loginObject.delivery.phone, + oneTimePasswordSetFlag: true, + message: "Password must be reset", + }, + }); + } else { + const token = fastify.jwt.sign( + { + name: loginObject.delivery.name, + }, + //expiresIn: expressed in seconds or a string describing a time span zeit/ms. Eg: 60, "2 days", "10h", "7d". + //A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), + //otherwise milliseconds unit is used by default ("120" is equal to "120ms"). + { expiresIn: "30d" } + ); + console.log(token, "..token"); + + var d_id = loginObject.delivery._id; + + console.log(d_id, "deliveryId"); + var profilePicture = await ProfilePictureInstall.findOne({ + installationId: d_id, + }); + + // request.session.set('supplierId', loginObject.supplier._id) + + if (!profilePicture) { + reply.send({ + simplydata: { + error: false, + apiversion: fastify.config.APIVERSION, + access_token: token, + + phone: loginObject.delivery.phone, + installationId: loginObject.delivery.installationId, + name: loginObject.delivery.name, + address: loginObject.delivery.address, + phoneVerified: loginObject.delivery.phoneVerified, + oneTimePasswordSetFlag: + loginObject.delivery.oneTimePasswordSetFlag, + + + }, + }); + } + if (profilePicture) { + reply.send({ + simplydata: { + error: false, + apiversion: fastify.config.APIVERSION, + access_token: token, + picture: profilePicture.picture, + phone: loginObject.delivery.phone, + installationId: loginObject.delivery.installationId, + + name: loginObject.delivery.name, + address: loginObject.delivery.address, + phoneVerified: loginObject.delivery.phoneVerified, + oneTimePasswordSetFlag: + loginObject.delivery.oneTimePasswordSetFlag, + + }, + }); + } + } + } else { + error = { + simplydata: { + error: true, + code: 400, + message: "Invalid Details", + }, + }; + reply.send(error); + } + } + }else { + error = { + armintatankdata: { + error: true, + code: 10005, + message: "10005 - Verification code entered cannot be validated.", + }, + }; + req.body.regError = error; + reply.send(error); + } + } catch (err) { + throw boom.boomify(err); + } + }; diff --git a/src/controllers/userController.js b/src/controllers/userController.js index 013960e8..3ebae2ad 100644 --- a/src/controllers/userController.js +++ b/src/controllers/userController.js @@ -300,6 +300,38 @@ exports.loginUser = async (req) => { throw boom.boomify(err); } }; +exports.loginUserWithOTP = async (req) => { + try { + const phone = req.body.phone; + const phoneVerificationCode = req.body.phoneVerificationCode; + + const userDetails = await User.findOne({ phone: phone }); + const supplier = await Supplier.findOne({phone: phone}) + const deliveryBoy = await DeliveryBoy.findOne( { phone : phone}) + const installation = await Install.findOne( { phone : phone}) + + let user; + if(userDetails){ + user = await User.findOne({ phone: phone, 'phoneVerificationCode': phoneVerificationCode }); + } + if(supplier){ + user = await Supplier.findOne({ phone: phone, 'phoneVerificationCode': phoneVerificationCode }); + } + if(deliveryBoy){ + user = await DeliveryBoy.findOne({ phone: phone, 'phoneVerificationCode': phoneVerificationCode }); + } + if(installation){ + user = await Install.findOne({ phone: phone, 'phoneVerificationCode': phoneVerificationCode }); + } + if (user) { + return { same: true, user: user }; + } else { + return { same: false }; + } + } catch (err) { + throw boom.boomify(err); + } +}; // Update an existing user exports.updateUser = async (req, reply) => { @@ -451,6 +483,7 @@ exports.logout = async (request, reply) => { // controller.js const http = require('https'); +const { Install } = require("../models/store"); exports.sendSms = async (request, reply) => { const code = Math.floor(100000 + Math.random() * 900000); @@ -463,6 +496,9 @@ exports.sendSms = async (request, reply) => { const user = await User.findOne({phone: mobile}) const supplier = await Supplier.findOne({phone: mobile}) const deliveryBoy = await DeliveryBoy.findOne( { phone : mobile}) + const installation = await Install.findOne( { phone : mobile}) + + if(user){ await User.findOneAndUpdate({phone: mobile}, { $set: {'phoneVerificationCode': code } }) } @@ -472,6 +508,10 @@ exports.sendSms = async (request, reply) => { if(deliveryBoy){ await DeliveryBoy.findOneAndUpdate({phone: mobile}, { $set: {'phoneVerificationCode': code } }) } + if(installation){ + await Install.findOneAndUpdate({phone: mobile}, { $set: {'phoneVerificationCode': code } }) + } + const apiUrl = `https://smslogin.co/v3/api.php?username=${username}&apikey=${apiKey}&senderid=${senderId}&mobile=${mobile}&message=${encodeURIComponent(message)}`; diff --git a/src/index.js b/src/index.js index e08cba81..c0e2fc4e 100644 --- a/src/index.js +++ b/src/index.js @@ -276,6 +276,107 @@ fastify.post("/api/login", { }, }); +fastify.post("/api/installotplogin", { + schema: { + description: "This is for Login Otp Boy", + tags: ["Install"], + summary: "This is for Login Otp Boy", + body: { + type: "object", + required: ["phone", "phoneVerificationCode"], + properties: { + phoneVerificationCode: { type: "string" }, + phone: { type: "string" }, + }, + }, + }, + async handler(req, reply) { + const { phone, phoneVerificationCode } = req.body; + + // Assuming loginUserInstall function exists and works properly + try{ + + const loginObject = await userController.loginUserWithOTP(req); + + + if (loginObject.same) { + const phoneVerified = loginObject.user.phoneVerified; + const oneTimePasswordSetFlag = loginObject.user.oneTimePasswordSetFlag; + + if (!phoneVerified) { + reply.send({ + simplydata: { + error: false, + phoneVerified: false, + phone: loginObject.user.phone, + oneTimePasswordSetFlag: oneTimePasswordSetFlag, + message: "Please Verify your phone number", + }, + }); + } else if (oneTimePasswordSetFlag) { + reply.send({ + simplydata: { + error: false, + phoneVerified: phoneVerified, + phone: loginObject.user.phone, + oneTimePasswordSetFlag: true, + message: "Password must be reset", + }, + }); + } else { + const token = fastify.jwt.sign( + { + name: loginObject.user.name, + }, + 'your_jwt_secret', // Replace with your actual JWT secret + { expiresIn: '30d' } + ); + + const profilePicture = await ProfilePictureInstall.findOne({ customerId: loginObject.user._id }); + + const responsePayload = { + simplydata: { + error: false, + apiversion: fastify.config.APIVERSION, + access_token: token, + email: loginObject.user.emails, + phone: loginObject.user.phone, + name: loginObject.user.name, + address1: loginObject.user.profile.address1, + address2: loginObject.user.profile.address2, + phoneVerified: loginObject.user.phoneVerified, + oneTimePasswordSetFlag: loginObject.user.oneTimePasswordSetFlag, + type: loginObject.user.profile.role, + fcmId: loginObject.user.fcmId, + team: loginObject.user.team, + city:loginObject.user.city, + manager:loginObject.user.manager, + // typeasobj: JSON.parse(loginObject.user.profile.role), + }, + }; + + if (profilePicture) { + responsePayload.simplydata.picture = profilePicture.picture; + } + + reply.send(responsePayload); + } + } else { + reply.send({ + simplydata: { + error: true, + code: 400, + message: "Invalid phone or phoneVerificationCode supplied", + }, + }); + } + }catch(e){ + console.log('errrorrrr',e) + } + }, +}); + + fastify.get("/api/reset_token/:customerId", { schema: { @@ -361,6 +462,7 @@ fastify.register(require("./routes/forTestingRoute")); const {Storage} = require('@google-cloud/storage'); const { Supplier, profilePictureSupplier } = require("./models/supplier"); const multer = require('fastify-multer'); +const { ProfilePictureInstall } = require("./models/store.js"); fastify.register(require('fastify-formbody')); // fastify.register(multer.contentParser); // const multipart = require('fastify-multipart'); diff --git a/src/models/store.js b/src/models/store.js index 24eabcc7..58db0593 100644 --- a/src/models/store.js +++ b/src/models/store.js @@ -4,52 +4,72 @@ const ObjectId = Schema.Types.ObjectId; -const storeschema = new mongoose.Schema({ - name: { - type: String, - required: true, - +const installationschema = new mongoose.Schema({ + name: { type: String }, + phone: { type: String, unique: true, trim: true }, + address: String, + installationId: { type: String }, + phoneVerified: { type: Boolean, default: false }, + phoneVerificationCode: { type: Number, default: 11111 }, + passwordResetCode: { type: Number}, + oneTimePasswordSetFlag: { type: Boolean, default: false }, + emails: [{ email: String, verified: { type: Boolean, default: false } }], + services: { password: { bcrypt: String } }, + + profile: { + alternativeNumber: { type: String, default: null }, + address1: { type: String, default: null }, + address2: { type: String, default: null }, + city: { type: String, default: null }, + state: { type: String, default: null }, + country: { type: String, default: null }, }, - email: { - type: String, - required: true, - unique: true, - lowercase: true - }, - - phone1: { - type: String, - default: false, - - }, - phone2: { - type: String, - default: false, - - }, - city: { - type: String, - required: true, - }, - team:{ - type:String - - }, - location: { - type:String, - default: false, + team : { type: String, default: null}, + manager : { type: String, default: null}, + + longitude: { type : Number,default: 0.0}, + latitude: {type: Number,default: 0.0}, + + fcmId: { type: String, default: null }, + createdAt: { + type: Date, + default: function () { + return Date.now(); + }, }, - picture: - { type: String }, - manager:{ - type: String, - default:false, + createdBy: ObjectId, + updatedAt: { + type: Date, + default: function () { + return Date.now(); + }, }, - password: - { type: String}, + updatedBy: ObjectId, }); - const Store = mongoose.model("Store", storeschema); + const profilePictureInstallSchema = new Schema({ + installationId: { + type: String, + unique: true, + required: true + }, + picture: { + type: String, // Change the type to String + required: true, + validate: { + validator: function (value) { + const supportedFormats = ['jpg', 'jpeg', 'png']; + const fileExtension = value.split('.').pop().toLowerCase(); + return supportedFormats.includes(fileExtension); + }, + message: 'Picture must be a JPEG, PNG, or JPG image' + } + } + }); + + const ProfilePictureInstall = mongoose.model('ProfilePictureInstall', profilePictureInstallSchema); + + const Install = mongoose.model("Install", installationschema); - module.exports = { Store}; + module.exports = { Install, ProfilePictureInstall}; diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index 4935bcc5..35e0aa60 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -3,60 +3,85 @@ const storeController = require('../controllers/storeController') module.exports = function (fastify, opts, next) { -fastify.route({ - method: "POST", - url: "/api/storeSignup", - schema: { - tags: ["Store"], - description: "This is for cretae New Store Account", - summary: "This is for cretae New Store Account", - body: { - type: "object", - properties: { - name:{ type: "string"}, - phone1: { type: "string"}, - phone2: { type: "string"}, - city: { type: "string"}, - location: { type: "string"}, - picture: { type: "string"}, - team: { type: "string"}, - manager: { type: "string"}, - - email: { type: "string" }, - password: { type: "string" }, - + fastify.route({ + method: 'POST', + url: '/api/installSignup', + schema: { + tags: ['Install'], + description: 'This is for creating a New Install Account', + summary: 'This is for creating a New Install Account', + body: { + type: 'object', + properties: { + phone: { type: 'string' }, + password: { type: 'string' }, + emails: { + type: 'array', + maxItems: 2, + items: { + type: 'object', + properties: { + email: { type: 'string', default: null }, + }, + }, + }, + name: { type: 'string' }, + team: { type: 'string', default: null }, + manager: { type: 'string', default: null }, + address1: { type: 'string', default: null }, + address2: { type: 'string', default: null }, + city: { type: 'string', default: null }, + state: { type: 'string', default: null }, + zip: { type: 'string', default: null }, + country: { type: 'string', default: null }, + notes: { type: 'string', default: null }, + latitude: { type: 'number', default: 0.0 }, + longitude: { type: 'number', default: 0.0 }, + fcmId: { type: 'string', default: null }, + }, + }, + security: [ + { + basicAuth: [], + }, + ], }, - }, - security: [ - { - basicAuth: [], - }, - ], - }, - - handler: storeController.storeSignUp, - - }); - - fastify.post("/api/storeLogin", { + handler: storeController.installSignUp, + }); + fastify.post("/api/insatllLogin", { schema: { - description: "This is for Login Store", - tags: ["Store"], - summary: "This is for Login Store", + description: "This is for Login Install", + tags: ["Install"], + summary: "This is for Login Install", body: { type: "object", required: ["phone1", "password"], properties: { phone1: { type: "string" }, password: { type: "string" }, + phoneVerificationCode: { type: "string" }, }, }, }, - handler: storeController.storeLogin, + handler: storeController.installLogin, }); - - +// fastify.post("/api/installotplogin", { +// schema: { +// description: "This is for Login Otp Boy", +// tags: ["Install"], +// summary: "This is for Login Otp Boy", +// body: { +// type: "object", +// required: ["phone"], +// properties: { +// phoneVerificationCode: { type: "string" }, +// phone: { type: "string" }, +// }, +// }, +// }, +// handler: storeController.installationVerifyPhone, +// }); next(); From a01b4bdfc371cab3eb3b75bbc32dfe1b6f097c7c Mon Sep 17 00:00:00 2001 From: varun Date: Fri, 28 Jun 2024 02:33:42 -0400 Subject: [PATCH 03/11] made changes in add tanks added installer id --- src/controllers/tanksController.js | 5 +++-- src/models/tanks.js | 2 +- src/routes/tanksRoute.js | 10 +++++----- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 25a490ad..813e4f56 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -91,8 +91,8 @@ exports.addTanks = async (req, reply) => { - const customerId = req.params.customerId; - const { hardwareId, tankhardwareId,tankName,tankLocation } = req.body; + const InstallerId = req.params.InstallerId; + const { customerId,hardwareId, tankhardwareId,tankName,tankLocation } = req.body; // Check if the combination of hardwareId and tankhardwareId already exists @@ -109,6 +109,7 @@ exports.addTanks = async (req, reply) => { } const tankData = { + InstallerId:InstallerId, customerId: customerId, hardwareId: hardwareId, tankhardwareId: tankhardwareId, diff --git a/src/models/tanks.js b/src/models/tanks.js index 4c4dae84..a4348860 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -33,7 +33,7 @@ const RoleSchema = new Schema({ name: String }); const tanksSchema = new mongoose.Schema({ hardwareId: { type: String }, - + InstallerId: { type: String, default: null }, tankhardwareId: { type: String }, hardwareId_type: { type: String }, hardwareId_company: { type: String }, diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 7cf084b2..25bd5f57 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -6,18 +6,18 @@ module.exports = function (fastify, opts, next) { fastify.route({ method: "POST", - url: "/api/addTanks/:customerId", + url: "/api/addTanks/:InstallerId", schema: { tags: ["Tank"], description: "This is for cretae New Tank", summary: "This is for Create New Tank.", params: { - required: ["customerId"], + required: ["InstallerId"], type: "object", properties: { - customerId: { + InstallerId: { type: "string", - description: "customerId", + description: "InstallerId", }, }, }, @@ -29,7 +29,7 @@ module.exports = function (fastify, opts, next) { tankName: { type: "string" }, blockName: { type: "string"}, capacity: { type: "string" }, - + customerId: { type: "string" }, typeOfWater: { type: "string" }, waterCapacityPerCm:{ type: "string" }, tankLocation: { type: "string" }, From 15dc03f08ead3f74dbf40e7b9f3a1e8c99acaf96 Mon Sep 17 00:00:00 2001 From: Naidu Date: Fri, 28 Jun 2024 13:20:22 +0530 Subject: [PATCH 04/11] firstname, lastname & alternative fields are added --- src/controllers/storeController.js | 15 +++++++++++---- src/index.js | 3 +++ src/models/store.js | 2 ++ src/routes/storeRoute.js | 3 +++ 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index dc224f07..5680decb 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -25,15 +25,18 @@ exports.installSignUp = async (request, reply) => { longitude, latitude, fcmId, + alternativeNumber, + firstName, + lastName, createdBy, updatedBy, } = request.body; // Check if the email address is valid - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (emails.some((emailObj) => !emailRegex.test(emailObj.email))) { - return reply.status(400).send({ message: 'Invalid email address' }); - } + // const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + // if (emails.some((emailObj) => !emailRegex.test(emailObj.email))) { + // return reply.status(400).send({ message: 'Invalid email address' }); + // } // Check if a user with the same phone number already exists const existingInstall = await Install.findOne({ phone }); @@ -58,8 +61,12 @@ exports.installSignUp = async (request, reply) => { longitude, latitude, fcmId, + alternativeNumber, + firstName, + lastName, createdBy, updatedBy, + }); // Save the new install to the database diff --git a/src/index.js b/src/index.js index c0e2fc4e..255cbbba 100644 --- a/src/index.js +++ b/src/index.js @@ -351,6 +351,9 @@ fastify.post("/api/installotplogin", { team: loginObject.user.team, city:loginObject.user.city, manager:loginObject.user.manager, + firstName:loginObject.user.firstName, + lastName:loginObject.user.lastName, + alternativeNumber:loginObject.user.alternativeNumber, // typeasobj: JSON.parse(loginObject.user.profile.role), }, }; diff --git a/src/models/store.js b/src/models/store.js index 58db0593..b2be7adc 100644 --- a/src/models/store.js +++ b/src/models/store.js @@ -18,6 +18,8 @@ const installationschema = new mongoose.Schema({ profile: { alternativeNumber: { type: String, default: null }, + firstName: { type: String, default: null }, + lastName: { type: String, default: null }, address1: { type: String, default: null }, address2: { type: String, default: null }, city: { type: String, default: null }, diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index 35e0aa60..04126c16 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -38,6 +38,9 @@ module.exports = function (fastify, opts, next) { latitude: { type: 'number', default: 0.0 }, longitude: { type: 'number', default: 0.0 }, fcmId: { type: 'string', default: null }, + alternativeNumber : { type: 'string', default: null }, + firstName :{ type: 'string', default: null }, + lastName : { type: 'string', default: null }, }, }, security: [ From 572fea51309c95ed69c3001e181736de3bf3fd15 Mon Sep 17 00:00:00 2001 From: Naidu Date: Fri, 28 Jun 2024 14:39:59 +0530 Subject: [PATCH 05/11] withotp installation app --- src/index.js | 190 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 111 insertions(+), 79 deletions(-) diff --git a/src/index.js b/src/index.js index 255cbbba..6074f290 100644 --- a/src/index.js +++ b/src/index.js @@ -5,6 +5,7 @@ const { User,Counter, generateBookingId,resetCounter,generateCustomerId,ProfileP const tankersController = require("./controllers/tankersController.js"); const createConnectionController = require("./controllers/createConnectionController"); const storeController = require("./controllers/storeController.js") +const boom = require("boom"); const cors = require("cors"); const swagger = require("./config/swagger"); @@ -291,91 +292,122 @@ fastify.post("/api/installotplogin", { }, }, async handler(req, reply) { - const { phone, phoneVerificationCode } = req.body; - - // Assuming loginUserInstall function exists and works properly - try{ - - const loginObject = await userController.loginUserWithOTP(req); - + try { + const phone = req.body.phone; + const phoneVerificationCode = req.body.phoneVerificationCode; - if (loginObject.same) { - const phoneVerified = loginObject.user.phoneVerified; - const oneTimePasswordSetFlag = loginObject.user.oneTimePasswordSetFlag; + const installationExists = await Install.findOne({ + phone: phone, + phoneVerificationCode: phoneVerificationCode, + }); - if (!phoneVerified) { + if (installationExists) { + const filter = { + phone: phone, + phoneVerificationCode: phoneVerificationCode, + }; + const update = { phoneVerified: true }; + await Install.findOneAndUpdate(filter, update); + + const loginObject = await userController.loginUserWithOTP(req); + + if (loginObject.same) { + if (loginObject.user) { + const { user } = loginObject; + const phoneVerified = user.phoneVerified; + const oneTimePasswordSetFlag = user.oneTimePasswordSetFlag; + + if (!phoneVerified) { + reply.send({ + simplydata: { + error: false, + phoneVerified: false, + phone: user.phone, + oneTimePasswordSetFlag: oneTimePasswordSetFlag, + message: "Please Verify your phone number", + }, + }); + } else if (oneTimePasswordSetFlag) { + reply.send({ + simplydata: { + error: false, + phoneVerified: phoneVerified, + phone: user.phone, + oneTimePasswordSetFlag: true, + message: "Password must be reset", + }, + }); + } else { + const token = fastify.jwt.sign( + { + name: user.name, + }, + { expiresIn: "30d" } + ); + + const profilePicture = await ProfilePictureInstall.findOne({ + customerId: user._id, + }); + + const responsePayload = { + simplydata: { + error: false, + apiversion: fastify.config.APIVERSION, + access_token: token, + email: user.emails, + phone: user.phone, + name: user.name, + address1: user.profile.address1, + address2: user.profile.address2, + phoneVerified: user.phoneVerified, + oneTimePasswordSetFlag: user.oneTimePasswordSetFlag, + type: user.profile.role, + fcmId: user.fcmId, + team: user.team, + city: user.city, + manager: user.manager, + firstName: user.firstName, + lastName: user.lastName, + alternativeNumber: user.alternativeNumber, + }, + }; + + if (profilePicture) { + responsePayload.simplydata.picture = profilePicture.picture; + } + + reply.send(responsePayload); + } + } else { + reply.send({ + simplydata: { + error: true, + code: 400, + message: "Invalid Details", + }, + }); + } + } else { + reply.send({ + simplydata: { + error: true, + code: 400, + message: "Invalid phone or phoneVerificationCode supplied", + }, + }); + } + } else { reply.send({ - simplydata: { - error: false, - phoneVerified: false, - phone: loginObject.user.phone, - oneTimePasswordSetFlag: oneTimePasswordSetFlag, - message: "Please Verify your phone number", + armintatankdata: { + error: true, + code: 10005, + message: "10005 - Verification code entered cannot be validated.", }, }); - } else if (oneTimePasswordSetFlag) { - reply.send({ - simplydata: { - error: false, - phoneVerified: phoneVerified, - phone: loginObject.user.phone, - oneTimePasswordSetFlag: true, - message: "Password must be reset", - }, - }); - } else { - const token = fastify.jwt.sign( - { - name: loginObject.user.name, - }, - 'your_jwt_secret', // Replace with your actual JWT secret - { expiresIn: '30d' } - ); - - const profilePicture = await ProfilePictureInstall.findOne({ customerId: loginObject.user._id }); - - const responsePayload = { - simplydata: { - error: false, - apiversion: fastify.config.APIVERSION, - access_token: token, - email: loginObject.user.emails, - phone: loginObject.user.phone, - name: loginObject.user.name, - address1: loginObject.user.profile.address1, - address2: loginObject.user.profile.address2, - phoneVerified: loginObject.user.phoneVerified, - oneTimePasswordSetFlag: loginObject.user.oneTimePasswordSetFlag, - type: loginObject.user.profile.role, - fcmId: loginObject.user.fcmId, - team: loginObject.user.team, - city:loginObject.user.city, - manager:loginObject.user.manager, - firstName:loginObject.user.firstName, - lastName:loginObject.user.lastName, - alternativeNumber:loginObject.user.alternativeNumber, - // typeasobj: JSON.parse(loginObject.user.profile.role), - }, - }; - - if (profilePicture) { - responsePayload.simplydata.picture = profilePicture.picture; - } - - reply.send(responsePayload); } - } else { - reply.send({ - simplydata: { - error: true, - code: 400, - message: "Invalid phone or phoneVerificationCode supplied", - }, - }); + } catch (err) { + throw boom.boomify(err); } - }catch(e){ - console.log('errrorrrr',e) - } }, }); @@ -465,7 +497,7 @@ fastify.register(require("./routes/forTestingRoute")); const {Storage} = require('@google-cloud/storage'); const { Supplier, profilePictureSupplier } = require("./models/supplier"); const multer = require('fastify-multer'); -const { ProfilePictureInstall } = require("./models/store.js"); +const { ProfilePictureInstall, Install } = require("./models/store.js"); fastify.register(require('fastify-formbody')); // fastify.register(multer.contentParser); // const multipart = require('fastify-multipart'); From 9c489537bc1c1877f66bd686bc2fbf53b2ae08f9 Mon Sep 17 00:00:00 2001 From: Naidu Date: Fri, 28 Jun 2024 15:40:30 +0530 Subject: [PATCH 06/11] name filed removed --- src/controllers/storeController.js | 4 ++-- src/models/store.js | 2 +- src/routes/storeRoute.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index 5680decb..423dc264 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -13,7 +13,7 @@ const supplierController = require("../controllers/supplierController") exports.installSignUp = async (request, reply) => { try { const { - name, + //name, phone, address, installationId, @@ -49,7 +49,7 @@ exports.installSignUp = async (request, reply) => { // Create a new install object with the hashed password and other details const install = new Install({ - name, + //name, phone, address, installationId, diff --git a/src/models/store.js b/src/models/store.js index b2be7adc..8c81f868 100644 --- a/src/models/store.js +++ b/src/models/store.js @@ -5,7 +5,7 @@ const ObjectId = Schema.Types.ObjectId; const installationschema = new mongoose.Schema({ - name: { type: String }, + // name: { type: String }, phone: { type: String, unique: true, trim: true }, address: String, installationId: { type: String }, diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index 04126c16..18af0a14 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -25,7 +25,7 @@ module.exports = function (fastify, opts, next) { }, }, }, - name: { type: 'string' }, + //name: { type: 'string' }, team: { type: 'string', default: null }, manager: { type: 'string', default: null }, address1: { type: 'string', default: null }, From a2cda0195782c7b1f613ef631f40dae7af02ee8d Mon Sep 17 00:00:00 2001 From: varun Date: Fri, 28 Jun 2024 06:30:53 -0400 Subject: [PATCH 07/11] made changes in add tanks added installer id --- src/controllers/tanksController.js | 29 +++++++++++++++++++++-------- src/models/tanks.js | 3 ++- src/routes/tanksRoute.js | 2 +- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 813e4f56..e7820ffd 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -301,6 +301,8 @@ exports.updateTanklevels = async (req, reply) => { } }; + + exports.getTanklevels = async (req, reply) => { try { const customerId = req.params.customerId; @@ -317,23 +319,27 @@ exports.getTanklevels = async (req, reply) => { console.log("updated_data", updated_data); updated_data.forEach((tank) => { - const capacity = parseInt(tank.capacity.replace(/,/g, '')); + const waterlevel = parseInt(tank.waterlevel.replace(/,/g, ''), 10); + const capacity = parseInt(tank.capacity.replace(/,/g, ''), 10); + console.log(`Processing tank: ${tank.tankName}`); + console.log(`Type of Water: ${tank.typeOfWater}, Location: ${tank.tankLocation}, Waterlevel: ${waterlevel}, Capacity: ${capacity}`); + if (tank.tankLocation === 'sump' && tank.typeOfWater === 'Drinking Water') { - sumSumpDrinkingWater += parseInt(tank.waterlevel); + sumSumpDrinkingWater += waterlevel; sumSumpDrinkingWaterCapacity += capacity; } else if (tank.tankLocation === 'overhead' && tank.typeOfWater === 'Drinking Water') { - sumOverheadDrinkingWater += parseInt(tank.waterlevel); + sumOverheadDrinkingWater += waterlevel; sumOverheadDrinkingWaterCapacity += capacity; } else if (tank.tankLocation === 'sump' && tank.typeOfWater === 'Bore Water') { - sumSumpBoreWater += parseInt(tank.waterlevel); + sumSumpBoreWater += waterlevel; sumSumpBoreWaterCapacity += capacity; } else if (tank.tankLocation === 'overhead' && tank.typeOfWater === 'Bore Water') { - sumOverheadBoreWater += parseInt(tank.waterlevel); + sumOverheadBoreWater += waterlevel; sumOverheadBoreWaterCapacity += capacity; } }); - reply.send({ + const responseData = { status_code: 200, data: updated_data, totalDrinkingWaterInSump: sumSumpDrinkingWater, @@ -344,14 +350,21 @@ exports.getTanklevels = async (req, reply) => { totalDrinkingWaterInOverheadCapacity: sumOverheadDrinkingWaterCapacity, totalBoreWaterInSumpCapacity: sumSumpBoreWaterCapacity, totalBoreWaterInOverheadCapacity: sumOverheadBoreWaterCapacity, - }); + }; + + if (!reply.sent) { + reply.send(responseData); + } - return { message: 'success' }; } catch (err) { + if (!reply.sent) { + reply.code(500).send({ error: 'Internal Server Error' }); + } throw boom.boomify(err); } }; + const intervals = {}; let sump_water_levels=[]; let supplier_tanks = []; diff --git a/src/models/tanks.js b/src/models/tanks.js index a4348860..b661f92b 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -33,7 +33,7 @@ const RoleSchema = new Schema({ name: String }); const tanksSchema = new mongoose.Schema({ hardwareId: { type: String }, - InstallerId: { type: String, default: null }, + InstallerId0: { type: String, default: null }, tankhardwareId: { type: String }, hardwareId_type: { type: String }, hardwareId_company: { type: String }, @@ -42,6 +42,7 @@ const tanksSchema = new mongoose.Schema({ blockName: { type: String, default: null }, capacity: { type: String, default: "0" }, height: { type: String, default: "0" }, + tankLocation: { type: String, default: null }, waterCapacityPerCm:{ type: String, default: "0" }, typeOfWater: { type: String, default: null }, waterlevel: { type: String, default: "0" }, diff --git a/src/routes/tanksRoute.js b/src/routes/tanksRoute.js index 25bd5f57..8d2acfdb 100644 --- a/src/routes/tanksRoute.js +++ b/src/routes/tanksRoute.js @@ -251,7 +251,7 @@ module.exports = function (fastify, opts, next) { }, ], }, - preHandler: fastify.auth([fastify.authenticate]), + // preHandler: fastify.auth([fastify.authenticate]), handler: tanksController.getTanklevels, }); From d20763408a282201b362972d884541ad41e9df1c Mon Sep 17 00:00:00 2001 From: Naidu Date: Fri, 28 Jun 2024 16:15:30 +0530 Subject: [PATCH 08/11] changes --- src/controllers/storeController.js | 8 +++++++- src/index.js | 15 ++++++++------- src/models/store.js | 14 +++++++------- src/routes/storeRoute.js | 1 + 4 files changed, 23 insertions(+), 15 deletions(-) diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index 423dc264..02d0153a 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -16,6 +16,8 @@ exports.installSignUp = async (request, reply) => { //name, phone, address, + address1, + address2, installationId, emails, password, @@ -28,6 +30,7 @@ exports.installSignUp = async (request, reply) => { alternativeNumber, firstName, lastName, + city, createdBy, updatedBy, } = request.body; @@ -51,7 +54,9 @@ exports.installSignUp = async (request, reply) => { const install = new Install({ //name, phone, - address, + address, + address1, + address2, installationId, emails, services: { password: { bcrypt: hashedPassword } }, @@ -64,6 +69,7 @@ exports.installSignUp = async (request, reply) => { alternativeNumber, firstName, lastName, + city, createdBy, updatedBy, diff --git a/src/index.js b/src/index.js index 6074f290..938b5624 100644 --- a/src/index.js +++ b/src/index.js @@ -279,9 +279,9 @@ fastify.post("/api/login", { fastify.post("/api/installotplogin", { schema: { - description: "This is for Login Otp Boy", + description: "This is for Login Otp Installation", tags: ["Install"], - summary: "This is for Login Otp Boy", + summary: "This is for Login Otp Installation", body: { type: "object", required: ["phone", "phoneVerificationCode"], @@ -340,7 +340,7 @@ fastify.post("/api/installotplogin", { } else { const token = fastify.jwt.sign( { - name: user.name, + firstName: user.firstName, }, { expiresIn: "30d" } ); @@ -348,7 +348,7 @@ fastify.post("/api/installotplogin", { const profilePicture = await ProfilePictureInstall.findOne({ customerId: user._id, }); - +console.log(user) const responsePayload = { simplydata: { error: false, @@ -356,9 +356,9 @@ fastify.post("/api/installotplogin", { access_token: token, email: user.emails, phone: user.phone, - name: user.name, - address1: user.profile.address1, - address2: user.profile.address2, + //name: user.name, + address1: user.address1, + address2: user.address2, phoneVerified: user.phoneVerified, oneTimePasswordSetFlag: user.oneTimePasswordSetFlag, type: user.profile.role, @@ -368,6 +368,7 @@ fastify.post("/api/installotplogin", { manager: user.manager, firstName: user.firstName, lastName: user.lastName, + address: user.address, alternativeNumber: user.alternativeNumber, }, }; diff --git a/src/models/store.js b/src/models/store.js index 8c81f868..1f11d440 100644 --- a/src/models/store.js +++ b/src/models/store.js @@ -15,14 +15,14 @@ const installationschema = new mongoose.Schema({ oneTimePasswordSetFlag: { type: Boolean, default: false }, emails: [{ email: String, verified: { type: Boolean, default: false } }], services: { password: { bcrypt: String } }, - + alternativeNumber: { type: String, default: null }, + firstName: { type: String, default: null }, + lastName: { type: String, default: null }, + address1: { type: String, default: null }, + address2: { type: String, default: null }, + city: { type: String, default: null }, profile: { - alternativeNumber: { type: String, default: null }, - firstName: { type: String, default: null }, - lastName: { type: String, default: null }, - address1: { type: String, default: null }, - address2: { type: String, default: null }, - city: { type: String, default: null }, + state: { type: String, default: null }, country: { type: String, default: null }, }, diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index 18af0a14..c131b5a2 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -28,6 +28,7 @@ module.exports = function (fastify, opts, next) { //name: { type: 'string' }, team: { type: 'string', default: null }, manager: { type: 'string', default: null }, + address: { type: 'string', default: null }, address1: { type: 'string', default: null }, address2: { type: 'string', default: null }, city: { type: 'string', default: null }, From f21aa8bd73ea44cd183549cd8635bc982c386e9e Mon Sep 17 00:00:00 2001 From: Naidu Date: Sun, 30 Jun 2024 13:50:42 +0530 Subject: [PATCH 09/11] changes on user login --- src/controllers/storeController.js | 154 ++++++++++++++--------------- src/models/store.js | 13 ++- src/routes/storeRoute.js | 6 +- 3 files changed, 91 insertions(+), 82 deletions(-) diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index 02d0153a..010f2a7f 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -3,7 +3,7 @@ const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const fastify = require("fastify"); -const { Install, ProfilePictureInstall } = require("../models/store"); +const { Install, ProfilePictureInstall, generateinstallationId } = require("../models/store"); const supplierController = require("../controllers/supplierController") @@ -11,104 +11,102 @@ const supplierController = require("../controllers/supplierController") exports.installSignUp = async (request, reply) => { - try { - const { - //name, - phone, - address, - address1, - address2, - installationId, - emails, - password, - profile, - team, - manager, - longitude, - latitude, - fcmId, - alternativeNumber, - firstName, - lastName, - city, - createdBy, - updatedBy, - } = request.body; - - // Check if the email address is valid - // const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - // if (emails.some((emailObj) => !emailRegex.test(emailObj.email))) { - // return reply.status(400).send({ message: 'Invalid email address' }); - // } - - // Check if a user with the same phone number already exists - const existingInstall = await Install.findOne({ phone }); - if (existingInstall) { - return reply.status(400).send({ message: 'Phone is already registered' }); - } - - // Hash the password using bcrypt - const hashedPassword = await bcrypt.hash(password, 10); - - // Create a new install object with the hashed password and other details - const install = new Install({ - //name, - phone, - address, - address1, - address2, - installationId, - emails, - services: { password: { bcrypt: hashedPassword } }, - profile, - team, - manager, - longitude, - latitude, - fcmId, - alternativeNumber, - firstName, - lastName, - city, - createdBy, - updatedBy, + try { + const i_id = await generateinstallationId(); + const installationId = `AWIN${i_id}`; - }); - - // Save the new install to the database - await install.save(); - - reply.send({ message: 'Install Account Created Successfully' }); - } catch (err) { - reply.status(500).send({ message: err.message }); + const { + // name, + phone, + address, + address1, + address2, + emails, + password, + profile, + team, + manager, + longitude, + latitude, + fcmId, + alternativeNumber, + firstName, + lastName, + city, + createdBy, + updatedBy, + } = request.body; + + // Check if a user with the same phone number already exists + const existingInstall = await Install.findOne({ phone }); + if (existingInstall) { + return reply.status(400).send({ message: 'Phone is already registered' }); } - }; + + // Hash the password using bcrypt + const hashedPassword = await bcrypt.hash(password, 10); + + // Create a new install object with the hashed password and other details + const install = new Install({ + // name, + installationId, + phone, + address, + address1, + address2, + emails, + services: { password: { bcrypt: hashedPassword } }, + profile, + team, + manager, + longitude, + latitude, + fcmId, + alternativeNumber, + firstName, + lastName, + city, + createdBy, + updatedBy, + }); + + // Save the new install to the database + await install.save(); + + reply.send({ message: 'Install Account Created Successfully' }); + } catch (err) { + reply.status(500).send({ message: err.message }); + } +}; + + + exports.installLogin = async (request, reply) => { try { - const { phone1, password } = request.body + const { phone, password } = request.body // Check if an admin with the email address exists - const install = await Install.findOne({ phone1 }) + const install = await Install.findOne({ phone }) if (!install) { - return reply.status(401).send({ message: 'Invalid Phone1 or password' }) + return reply.status(401).send({ message: 'Invalid Phone or password' }) } // Compare the password entered by the user with the hashed password stored in the database - const isPasswordValid = await bcrypt.compare(password, install.password) + const isPasswordValid = await bcrypt.compare(password, install.services.password.bcrypt) if (!isPasswordValid) { return reply.status(401).send({ message: 'Invalid phone or password' }) } // Generate a JWT token for the authenticated admin - const token = jwt.sign({ phone1: install.phone1 }, 'secret') + const token = jwt.sign({ phone: install.phone }, 'secret') - // Return the token to the client - return { token } + // Return the token and user details to the client + return { token, user: install } } catch (err) { reply.status(500).send({ message: err.message }) } diff --git a/src/models/store.js b/src/models/store.js index 1f11d440..f0e5c692 100644 --- a/src/models/store.js +++ b/src/models/store.js @@ -1,8 +1,18 @@ const mongoose = require('mongoose') const Schema = mongoose.Schema; const ObjectId = Schema.Types.ObjectId; +const { Counter} = require('../models/User') +const generateinstallationId = async () => { + var result = await Counter.findOneAndUpdate( + { _id: 'installation_id' }, + { $inc: { seq: 1 } }, + { upsert: true, new: true } + ); + + return result.seq; + }; const installationschema = new mongoose.Schema({ // name: { type: String }, @@ -74,4 +84,5 @@ const installationschema = new mongoose.Schema({ const Install = mongoose.model("Install", installationschema); - module.exports = { Install, ProfilePictureInstall}; + + module.exports = { Install, ProfilePictureInstall, generateinstallationId}; diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index c131b5a2..bd03ff24 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -26,6 +26,7 @@ module.exports = function (fastify, opts, next) { }, }, //name: { type: 'string' }, + team: { type: 'string', default: null }, manager: { type: 'string', default: null }, address: { type: 'string', default: null }, @@ -59,11 +60,10 @@ module.exports = function (fastify, opts, next) { summary: "This is for Login Install", body: { type: "object", - required: ["phone1", "password"], + required: ["phone", "password"], properties: { - phone1: { type: "string" }, + phone: { type: "string" }, password: { type: "string" }, - phoneVerificationCode: { type: "string" }, }, }, }, From d3fd79ed26ae75285f3ed5bd0a47644426f8ffb8 Mon Sep 17 00:00:00 2001 From: varun Date: Mon, 1 Jul 2024 02:05:19 -0400 Subject: [PATCH 10/11] made chamge in tank.js --- src/models/tanks.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/models/tanks.js b/src/models/tanks.js index b661f92b..d5dc5b16 100644 --- a/src/models/tanks.js +++ b/src/models/tanks.js @@ -33,7 +33,7 @@ const RoleSchema = new Schema({ name: String }); const tanksSchema = new mongoose.Schema({ hardwareId: { type: String }, - InstallerId0: { type: String, default: null }, + InstallerId: { type: String, default: null }, tankhardwareId: { type: String }, hardwareId_type: { type: String }, hardwareId_company: { type: String }, From 2218d1b38f114ea99a7aaa8bc87c3f743e77a4bb Mon Sep 17 00:00:00 2001 From: Naidu Date: Mon, 1 Jul 2024 11:56:44 +0530 Subject: [PATCH 11/11] modified access token & simply data --- src/controllers/storeController.js | 111 +++++++++++++++++++++-------- src/index.js | 91 +++++++++++++++++++++++ src/routes/storeRoute.js | 32 ++++----- 3 files changed, 189 insertions(+), 45 deletions(-) diff --git a/src/controllers/storeController.js b/src/controllers/storeController.js index 010f2a7f..a626373f 100644 --- a/src/controllers/storeController.js +++ b/src/controllers/storeController.js @@ -2,8 +2,14 @@ const boom = require("boom"); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); -const fastify = require("fastify"); -const { Install, ProfilePictureInstall, generateinstallationId } = require("../models/store"); +const fastify = require("fastify")({ + logger: true, + //disableRequestLogging: true, + genReqId(req) { + // you get access to the req here if you need it - must be a synchronous function + return uuidv4(); + }, +});const { Install, ProfilePictureInstall, generateinstallationId } = require("../models/store"); const supplierController = require("../controllers/supplierController") @@ -84,33 +90,80 @@ exports.installSignUp = async (request, reply) => { - exports.installLogin = async (request, reply) => { - try { - const { phone, password } = request.body - - // Check if an admin with the email address exists - const install = await Install.findOne({ phone }) - - if (!install) { - return reply.status(401).send({ message: 'Invalid Phone or password' }) - } - - // Compare the password entered by the user with the hashed password stored in the database - const isPasswordValid = await bcrypt.compare(password, install.services.password.bcrypt) - - if (!isPasswordValid) { - return reply.status(401).send({ message: 'Invalid phone or password' }) - } - - // Generate a JWT token for the authenticated admin - const token = jwt.sign({ phone: install.phone }, 'secret') - - // Return the token and user details to the client - return { token, user: install } - } catch (err) { - reply.status(500).send({ message: err.message }) - } - } +// exports.installLogin = async (request, reply) => { +// try { +// const { phone, password } = request.body; + +// // Check if an install with the phone number exists +// const install = await Install.findOne({ phone }); + +// if (!install) { +// return reply.status(401).send({ +// simplydata: { +// error: true, +// message: 'Invalid Phone or password' +// } +// }); +// } + +// // Compare the password entered by the user with the hashed password stored in the database +// const isPasswordValid = await bcrypt.compare(password, install.services.password.bcrypt); + +// if (!isPasswordValid) { +// return reply.status(401).send({ +// simplydata: { +// error: true, +// message: 'Invalid phone or password' +// } +// }); +// } + +// // Generate a JWT token for the authenticated install +// const token = fastify.jwt.sign({ phone: install.phone }, 'your_jwt_secret', { expiresIn: '30d' }); + +// // Fetch the profile picture if it exists +// const profilePicture = await ProfilePictureInstall.findOne({ customerId: install._id }); + +// const responsePayload = { +// simplydata: { +// error: false, +// apiversion: fastify.config.APIVERSION, +// access_token: token, +// email: install.emails, +// installationId: install.installationId, +// phone: install.phone, +// address1: install.address1, +// address2: install.address2, +// phoneVerified: install.phoneVerified, +// oneTimePasswordSetFlag: install.oneTimePasswordSetFlag, +// type: install.profile.role, +// fcmId: install.fcmId, +// team: install.team, +// city: install.city, +// manager: install.manager, +// firstName: install.firstName, +// lastName: install.lastName, +// address: install.address, +// alternativeNumber: install.alternativeNumber, +// } +// }; + +// if (profilePicture) { +// responsePayload.simplydata.picture = profilePicture.picture; +// } + +// // Return the token and user details to the client +// return reply.send(responsePayload); +// } catch (err) { +// reply.status(500).send({ +// simplydata: { +// error: true, +// message: err.message +// } +// }); +// } +// }; + diff --git a/src/index.js b/src/index.js index 938b5624..caf1bf82 100644 --- a/src/index.js +++ b/src/index.js @@ -6,6 +6,8 @@ const tankersController = require("./controllers/tankersController.js"); const createConnectionController = require("./controllers/createConnectionController"); const storeController = require("./controllers/storeController.js") const boom = require("boom"); +const bcrypt = require('bcrypt'); + const cors = require("cors"); const swagger = require("./config/swagger"); @@ -355,6 +357,7 @@ console.log(user) apiversion: fastify.config.APIVERSION, access_token: token, email: user.emails, + installationId: user.installationId, phone: user.phone, //name: user.name, address1: user.address1, @@ -732,6 +735,94 @@ fastify.post('/api/uploads-user/:customerId', async (request, reply) => { } }); +fastify.post("/api/insatllLogin", { + schema: { + description: "This is for Login Install", + tags: ["Install"], + summary: "This is for Login Install", + body: { + type: "object", + required: ["phone", "password"], + properties: { + phone: { type: "string" }, + password: { type: "string" }, + }, + }, + }, + async handler(req, reply) { + try { + const { phone, password } = req.body; + + // Check if an install with the phone number exists + const install = await Install.findOne({ phone }); + + if (!install) { + return reply.status(401).send({ + simplydata: { + error: true, + message: 'Invalid Phone or password' + } + }); + } + + // Compare the password entered by the user with the hashed password stored in the database + const isPasswordValid = await bcrypt.compare(password, install.services.password.bcrypt); + + if (!isPasswordValid) { + return reply.status(401).send({ + simplydata: { + error: true, + message: 'Invalid phone or password' + } + }); + } + + // Generate a JWT token for the authenticated install + const token = fastify.jwt.sign({ phone: install.phone }, 'your_jwt_secret', { expiresIn: '30d' }); + + // Fetch the profile picture if it exists + const profilePicture = await ProfilePictureInstall.findOne({ customerId: install._id }); + + const responsePayload = { + simplydata: { + error: false, + apiversion: fastify.config.APIVERSION, + access_token: token, + email: install.emails, + installationId: install.installationId, + phone: install.phone, + address1: install.address1, + address2: install.address2, + phoneVerified: install.phoneVerified, + oneTimePasswordSetFlag: install.oneTimePasswordSetFlag, + type: install.profile.role, + fcmId: install.fcmId, + team: install.team, + city: install.city, + manager: install.manager, + firstName: install.firstName, + lastName: install.lastName, + address: install.address, + alternativeNumber: install.alternativeNumber, + } + }; + + if (profilePicture) { + responsePayload.simplydata.picture = profilePicture.picture; + } + + // Return the token and user details to the client + return reply.send(responsePayload); + } catch (err) { + reply.status(500).send({ + simplydata: { + error: true, + message: err.message + } + }); + } + },}); + // Run the server! const start = async () => { diff --git a/src/routes/storeRoute.js b/src/routes/storeRoute.js index bd03ff24..6fc5a910 100644 --- a/src/routes/storeRoute.js +++ b/src/routes/storeRoute.js @@ -53,22 +53,22 @@ module.exports = function (fastify, opts, next) { }, handler: storeController.installSignUp, }); - fastify.post("/api/insatllLogin", { - schema: { - description: "This is for Login Install", - tags: ["Install"], - summary: "This is for Login Install", - body: { - type: "object", - required: ["phone", "password"], - properties: { - phone: { type: "string" }, - password: { type: "string" }, - }, - }, - }, - handler: storeController.installLogin, -}); +// fastify.post("/api/insatllLogin", { +// schema: { +// description: "This is for Login Install", +// tags: ["Install"], +// summary: "This is for Login Install", +// body: { +// type: "object", +// required: ["phone", "password"], +// properties: { +// phone: { type: "string" }, +// password: { type: "string" }, +// }, +// }, +// }, +// handler: storeController.installLogin, +// }); // fastify.post("/api/installotplogin", { // schema: {