From dbc2e0fddae4d1773b6bb9aaee068668fa7b595f Mon Sep 17 00:00:00 2001 From: geeknk Date: Tue, 28 Nov 2023 19:24:08 +0530 Subject: [PATCH] applied redis with refresh token --- app.js | 3 +- config/redisconfig.js | 17 + controllers/userController.js | 11 +- middleware/usermiddle.js | 28 +- migrations/20231125074458-create-address.js | 10 +- models/address.js | 3 +- package-lock.json | 146 +++++++ package.json | 1 + routes/userRoute.js | 2 + services/userservices.js | 416 +++++++++++--------- 10 files changed, 436 insertions(+), 201 deletions(-) create mode 100644 config/redisconfig.js diff --git a/app.js b/app.js index 767bbcd..9c794cf 100644 --- a/app.js +++ b/app.js @@ -1,13 +1,14 @@ const express = require("express"); const service = require("./config/constant.js"); const userRoute = require("./routes/userRoute.js"); +const rdcon = require("./config/redisconfig.js") const app = express(); app.use(express.json()); app.use("/user", userRoute) - +rdcon.redisconnect(); app.listen(service.port,()=>{ console.log("server is running"); }) \ No newline at end of file diff --git a/config/redisconfig.js b/config/redisconfig.js new file mode 100644 index 0000000..f48934e --- /dev/null +++ b/config/redisconfig.js @@ -0,0 +1,17 @@ +const { createClient } = require('redis'); + +const client = createClient(); + +const redisconnect = async () =>{ + try { + await client.connect(); + console.log("database connected"); + } catch (error) { + console.log(error); + } +} + +module.exports = { + client, + redisconnect +} diff --git a/controllers/userController.js b/controllers/userController.js index f5bef48..5b13a84 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -20,7 +20,7 @@ exports.signin = async (req, res) => { res.cookie('jwt', loggedin.refreshToken, { httpOnly: true, sameSite: 'None', secure: true, maxAge: 24 * 60 * 60 * 1000 - }); + }); res.status(200).send(loggedin.accessToken); } }; @@ -165,4 +165,13 @@ exports.aggregate = async (req,res) => { } catch (error) { res.status(401).send({success: "false",error}); } +} + +exports.refreshuser = async (req,res) => { + try { + const token = await userServices.generateToken(req.data.email) + res.status(200).send(token); + } catch (error) { + res.status(401).send({success: "false",error}); + } } \ No newline at end of file diff --git a/middleware/usermiddle.js b/middleware/usermiddle.js index 8603e92..0cab46f 100644 --- a/middleware/usermiddle.js +++ b/middleware/usermiddle.js @@ -2,7 +2,7 @@ require("dotenv").config(); const jwt = require("jsonwebtoken"); const config = require("../config/constant"); const multer = require("multer") -const {User} = require("../models") +const {User} = require("../models"); exports.verifyEmail = async (req, res, next) => { const userData = await User.findOne({where:{ email: req.body.email }}); @@ -19,7 +19,7 @@ exports.checkAuth = async (req, res, next) => { if (typeof bearerHeader !== "undefined") { const bearer = bearerHeader.split(" "); const token = bearer[1]; - const {email,id}=jwt.verify(token, config.secretKey); + const {email,id}=jwt.verify(token, config.ACCESS_TOKEN_SECRET); req.data= {email, token, id} next(); } else { @@ -27,6 +27,30 @@ exports.checkAuth = async (req, res, next) => { } }; +exports.verifyRT = async (req,res,next) =>{ + if (req.cookies?.jwt) { + + // Destructuring refreshToken from cookie + const refreshToken = req.cookies.jwt; + + // Verifying refresh token + jwt.verify(refreshToken, config.REFRESH_TOKEN_SECRET, + (err, decoded) => { + if (err) { + // Wrong Refesh Token + return res.status(406).json({ message: 'Unauthorized' }); + } + else { + // Correct token we send a new access token + req.data = email; + next(); + } + }) + } else { + return res.status(406).json({ message: 'Unauthorized' }); + } +} + exports.upload = multer({ storage:multer.diskStorage({ destination: function (req,file,cb){ diff --git a/migrations/20231125074458-create-address.js b/migrations/20231125074458-create-address.js index ee5e484..e8f2328 100644 --- a/migrations/20231125074458-create-address.js +++ b/migrations/20231125074458-create-address.js @@ -11,11 +11,11 @@ module.exports = { }, user_id: { type: Sequelize.INTEGER, - references:{ - model:"Users", - key:"id", - as:"id" - } + // references:{ + // model:"Users", + // key:"id", + // as:"id" + // } }, address: { type: Sequelize.STRING diff --git a/models/address.js b/models/address.js index 3a67755..11a99f9 100644 --- a/models/address.js +++ b/models/address.js @@ -11,7 +11,8 @@ module.exports = (sequelize, DataTypes) => { // define association here address.belongsTo(models.User, { foreignKey: "user_id", - onDelete:"CASCADE" + onDelete:"CASCADE", + hooks:true }); } } diff --git a/package-lock.json b/package-lock.json index b9dc9d6..b7874df 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,6 +20,7 @@ "mysql2": "^3.6.5", "nodemailer": "^6.9.7", "nodemon": "^3.0.1", + "redis": "^4.6.11", "sequelize": "^6.35.1", "sequelize-cli": "^6.6.2" } @@ -54,6 +55,59 @@ "node": ">=14" } }, + "node_modules/@redis/bloom": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz", + "integrity": "sha512-HG2DFjYKbpNmVXsa0keLHp/3leGJz1mjh09f2RLGGLQZzSHpkmZWuwJbAvo3QcRY8p80m5+ZdXZdYOSBLlp7Cg==", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/client": { + "version": "1.5.12", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-1.5.12.tgz", + "integrity": "sha512-/ZjE18HRzMd80eXIIUIPcH81UoZpwulbo8FmbElrjPqH0QC0SeIKu1BOU49bO5trM5g895kAjhvalt5h77q+4A==", + "dependencies": { + "cluster-key-slot": "1.1.2", + "generic-pool": "3.9.0", + "yallist": "4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@redis/graph": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@redis/graph/-/graph-1.1.1.tgz", + "integrity": "sha512-FEMTcTHZozZciLRl6GiiIB4zGm5z5F3F6a6FZCyrfxdKOhFlGkiAqlexWMBzCi4DcRoyiOsuLfW+cjlGWyExOw==", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/json": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@redis/json/-/json-1.0.6.tgz", + "integrity": "sha512-rcZO3bfQbm2zPRpqo82XbW8zg4G/w4W3tI7X8Mqleq9goQjAGLL7q/1n1ZX4dXEAmORVZ4s1+uKLaUOg7LrUhw==", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/search": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@redis/search/-/search-1.1.6.tgz", + "integrity": "sha512-mZXCxbTYKBQ3M2lZnEddwEAks0Kc7nauire8q20oA0oA/LoA+E/b5Y5KZn232ztPb1FkIGqo12vh3Lf+Vw5iTw==", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/time-series": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-1.0.5.tgz", + "integrity": "sha512-IFjIgTusQym2B5IZJG3XKr5llka7ey84fw/NOYqESP5WUfQs9zz1ww/9+qoz4ka/S6KcGBodzlCeZ5UImKbscg==", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, "node_modules/@types/debug": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", @@ -433,6 +487,14 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -1043,6 +1105,14 @@ "is-property": "^1.0.2" } }, + "node_modules/generic-pool": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/generic-pool/-/generic-pool-3.9.0.tgz", + "integrity": "sha512-hymDOu5B53XvN4QT9dBmZxPX4CWhBPPLguTZ9MMFeFa/Kg0xWVfylOVNlJji/E7yTZWFd/q9GO5TxDLq156D7g==", + "engines": { + "node": ">= 4" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -1993,6 +2063,19 @@ "node": ">=8.10.0" } }, + "node_modules/redis": { + "version": "4.6.11", + "resolved": "https://registry.npmjs.org/redis/-/redis-4.6.11.tgz", + "integrity": "sha512-kg1Lt4NZLYkAjPOj/WcyIGWfZfnyfKo1Wg9YKVSlzhFwxpFIl3LYI8BWy1Ab963LLDsTz2+OwdsesHKljB3WMQ==", + "dependencies": { + "@redis/bloom": "1.2.0", + "@redis/client": "1.5.12", + "@redis/graph": "1.1.1", + "@redis/json": "1.0.6", + "@redis/search": "1.1.6", + "@redis/time-series": "1.0.5" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -2823,6 +2906,46 @@ "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", "optional": true }, + "@redis/bloom": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz", + "integrity": "sha512-HG2DFjYKbpNmVXsa0keLHp/3leGJz1mjh09f2RLGGLQZzSHpkmZWuwJbAvo3QcRY8p80m5+ZdXZdYOSBLlp7Cg==", + "requires": {} + }, + "@redis/client": { + "version": "1.5.12", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-1.5.12.tgz", + "integrity": "sha512-/ZjE18HRzMd80eXIIUIPcH81UoZpwulbo8FmbElrjPqH0QC0SeIKu1BOU49bO5trM5g895kAjhvalt5h77q+4A==", + "requires": { + "cluster-key-slot": "1.1.2", + "generic-pool": "3.9.0", + "yallist": "4.0.0" + } + }, + "@redis/graph": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@redis/graph/-/graph-1.1.1.tgz", + "integrity": "sha512-FEMTcTHZozZciLRl6GiiIB4zGm5z5F3F6a6FZCyrfxdKOhFlGkiAqlexWMBzCi4DcRoyiOsuLfW+cjlGWyExOw==", + "requires": {} + }, + "@redis/json": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@redis/json/-/json-1.0.6.tgz", + "integrity": "sha512-rcZO3bfQbm2zPRpqo82XbW8zg4G/w4W3tI7X8Mqleq9goQjAGLL7q/1n1ZX4dXEAmORVZ4s1+uKLaUOg7LrUhw==", + "requires": {} + }, + "@redis/search": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@redis/search/-/search-1.1.6.tgz", + "integrity": "sha512-mZXCxbTYKBQ3M2lZnEddwEAks0Kc7nauire8q20oA0oA/LoA+E/b5Y5KZn232ztPb1FkIGqo12vh3Lf+Vw5iTw==", + "requires": {} + }, + "@redis/time-series": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-1.0.5.tgz", + "integrity": "sha512-IFjIgTusQym2B5IZJG3XKr5llka7ey84fw/NOYqESP5WUfQs9zz1ww/9+qoz4ka/S6KcGBodzlCeZ5UImKbscg==", + "requires": {} + }, "@types/debug": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", @@ -3117,6 +3240,11 @@ } } }, + "cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==" + }, "color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -3576,6 +3704,11 @@ "is-property": "^1.0.2" } }, + "generic-pool": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/generic-pool/-/generic-pool-3.9.0.tgz", + "integrity": "sha512-hymDOu5B53XvN4QT9dBmZxPX4CWhBPPLguTZ9MMFeFa/Kg0xWVfylOVNlJji/E7yTZWFd/q9GO5TxDLq156D7g==" + }, "get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -4293,6 +4426,19 @@ "picomatch": "^2.2.1" } }, + "redis": { + "version": "4.6.11", + "resolved": "https://registry.npmjs.org/redis/-/redis-4.6.11.tgz", + "integrity": "sha512-kg1Lt4NZLYkAjPOj/WcyIGWfZfnyfKo1Wg9YKVSlzhFwxpFIl3LYI8BWy1Ab963LLDsTz2+OwdsesHKljB3WMQ==", + "requires": { + "@redis/bloom": "1.2.0", + "@redis/client": "1.5.12", + "@redis/graph": "1.1.1", + "@redis/json": "1.0.6", + "@redis/search": "1.1.6", + "@redis/time-series": "1.0.5" + } + }, "require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", diff --git a/package.json b/package.json index f720b53..82ba099 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "mysql2": "^3.6.5", "nodemailer": "^6.9.7", "nodemon": "^3.0.1", + "redis": "^4.6.11", "sequelize": "^6.35.1", "sequelize-cli": "^6.6.2" }, diff --git a/routes/userRoute.js b/routes/userRoute.js index cc8b249..716769c 100644 --- a/routes/userRoute.js +++ b/routes/userRoute.js @@ -7,6 +7,8 @@ router.get("/register",mid.verifyEmail,controller.signup); router.get("/get",mid.checkAuth,controller.getuser); router.post("/auth/signin",controller.signin); router.post("/address",mid.checkAuth,controller.user_address); +router.put("/delete",mid.checkAuth,controller.deluser); +router.put("/refresh",mid.verifyRT,controller.refreshuser); module.exports = router \ No newline at end of file diff --git a/services/userservices.js b/services/userservices.js index 67bc2e0..6da8161 100644 --- a/services/userservices.js +++ b/services/userservices.js @@ -1,178 +1,189 @@ const config = require("../config/constant"); -const {User} = require("../models"); -const {userToken} = require("../models"); -const {address} = require("../models"); +const { User } = require("../models"); +const { userToken } = require("../models"); +const { address } = require("../models"); const jwt = require("jsonwebtoken"); const bcrypt = require("bcryptjs"); -const nodemailer = require("nodemailer") +const nodemailer = require("nodemailer"); const axios = require("axios"); -const Cheerio =require("cheerio"); +const Cheerio = require("cheerio"); +const { client } = require("../config/redisconfig"); const transporter = nodemailer.createTransport({ - host:'smtp.gmail.com', - port:587, - secure:false, - requireTLS:true, - auth:{ - user:"ernitish26@gmail.com", - pass: config.EMAIL_PASS - } + host: "smtp.gmail.com", + port: 587, + secure: false, + requireTLS: true, + auth: { + user: "ernitish26@gmail.com", + pass: config.EMAIL_PASS, + }, }); const getdata = async (id) => { try { - return await User.findOne({include: address},{where:{id:id}}); + return await User.findOne({ include: address }, { where: { id: id } }); } catch (error) { console.error("Error retrieving data:", error); throw error; } }; - -const deleteuser = async (ID)=>{ - const data = await User.destroy({ - where: { - id: ID - } - }); +const deleteuser = async (ID) => { + const data1 = await address.destroy({ where: { user_id: ID } }); + const data = await User.destroy({ where: { id: ID } }); if (data) { - return true + return true; } -} +}; -const updateuser1 = async (data, body_data)=>{ - await users.updateOne(data.email, body_data); -} +const updateuser1 = async (data, body_data) => { + await users.updateOne(data.email, body_data); +}; const matchpass = async (data) => { - return data.password===data.new_password -} + return data.password === data.new_password; +}; -const verifyemail = async (data) =>{ - const emailexist = await users.findOne({ email: data.email }); +const verifyemail = async (data) => { + const emailexist = await users.findOne({ email: data.email }); - if(emailexist){ + if (emailexist) { const token = jwt.sign( - { email: emailexist.email, id: emailexist._id }, - config.ACCESS_TOKEN_SECRET, - {expiresIn:config.FPASS_EXPIRESIN} - ); - - const mailOption ={ - from: config.EMAIL_FROM, - to: config.EMAIL_TO, - subject: "Password Reset Link", - html: `${token}` - } - transporter.sendMail(mailOption); - return token; - }else{ - return false - } -} + { email: emailexist.email, id: emailexist._id }, + config.ACCESS_TOKEN_SECRET, + { expiresIn: config.FPASS_EXPIRESIN } + ); -const modifyPass = async(email,data) =>{ - await users.updateOne( - { email }, - { - password: data.password, - } - ); - const mailOption ={ + const mailOption = { from: config.EMAIL_FROM, to: config.EMAIL_TO, - subject: "Password Reset", - text: "Password Reset successfully" - } + subject: "Password Reset Link", + html: `${token}`, + }; transporter.sendMail(mailOption); -} + return token; + } else { + return false; + } +}; -const userlogin = async(data) =>{ - const userData = await User.findOne({where: { email: data.email} }); - const pass = bcrypt.compare(userData.password , data.password) - - if(pass && userData){ - const accessToken = jwt.sign( - { email: userData.email, id: userData.id }, - config.ACCESS_TOKEN_SECRET, - {expiresIn:config.ACCESS_TOKEN_EXPIRES} - ); - const refreshToken = jwt.sign({ - username: userData.email, id:userData.id, - }, config.REFRESH_TOKEN_SECRET, - { expiresIn: '1d' }); - - await userToken.create({ - user_id:userData.id, - token: accessToken, - expiry: config.JWT_EXPIRES_IN - }); - return {accessToken,refreshToken}; - }else{ - return false +const modifyPass = async (email, data) => { + await users.updateOne( + { email }, + { + password: data.password, } -} + ); + const mailOption = { + from: config.EMAIL_FROM, + to: config.EMAIL_TO, + subject: "Password Reset", + text: "Password Reset successfully", + }; + transporter.sendMail(mailOption); +}; -const usersignup = async(data) =>{ - let user = await User.create(data); - if(user){ - const mailOption ={ - from: config.EMAIL_FROM, - to: config.EMAIL_TO, - subject: "Registration", - text: "You Have been Registered successfully" - } - transporter.sendMail(mailOption); - return user; - }else{ - return false; - } +const userlogin = async (data) => { + const userData = await User.findOne({ where: { email: data.email } }); + const pass = bcrypt.compare(userData.password, data.password); + + if (pass && userData) { + const accessToken = jwt.sign( + { email: userData.email, id: userData.id }, + config.ACCESS_TOKEN_SECRET, + { expiresIn: config.ACCESS_TOKEN_EXPIRES } + ); + const refreshToken = jwt.sign( + { + username: userData.email, + id: userData.id, + }, + config.REFRESH_TOKEN_SECRET, + { expiresIn: "1d" } + ); + + await userToken.create({ + user_id: userData.id, + token: accessToken, + expiry: config.JWT_EXPIRES_IN, + }); + await client.hSet("refreshToken", { + email: userData.email, + username: userData.username, + }); + return { accessToken, refreshToken }; + } else { + return false; + } }; -const user_list = async (page)=>{ - const firstindex = (page - 1)*10; - const lastindex = page *10; - const data= await users.find(); - const sliced_data = data.slice(firstindex, lastindex); - return sliced_data; -} +const usersignup = async (data) => { + let user = await User.create(data); + if (user) { + const mailOption = { + from: config.EMAIL_FROM, + to: config.EMAIL_TO, + subject: "Registration", + text: "You Have been Registered successfully", + }; + transporter.sendMail(mailOption); + return user; + } else { + return false; + } +}; -const useraddress = async (data,ID) => { - try { - address.sync(); - let userAdd = await address.create({ - user_id: ID, - address: data.address, - city: data.city, - state: data.state, - pin_code: data.pin_code, - phone: data.phone - }); - return userAdd - } catch (error) { - console.error(error) - } +const user_list = async (page) => { + const firstindex = (page - 1) * 10; + const lastindex = page * 10; + const data = await users.find(); + const sliced_data = data.slice(firstindex, lastindex); + return sliced_data; +}; + +const useraddress = async (data, ID) => { + try { + address.sync(); + let userAdd = await address.create({ + user_id: ID, + address: data.address, + city: data.city, + state: data.state, + pin_code: data.pin_code, + phone: data.phone, + }); + return userAdd; + } catch (error) { + console.error(error); + } }; -const flipkart = async ()=>{ +const flipkart = async () => { const movie = []; - try{ - await axios.get(config.URL) - .then((response)=>{ - let $ = Cheerio.load(response.data); - $('._2n7i6c').each(function(el, index){ - const name = ($(this).find('a._2rpwqI').attr('title')); - const price = ($(this).find('div._30jeq3').text()); - const link = ($(this).find('a.s1Q9rs').attr('href')); - const rating = ($(this).find('div._3LWZlK').text()); - const discount = ($(this).find('div._3Ay6Sb').text().split(" ")[0]); + try { + await axios.get(config.URL).then((response) => { + let $ = Cheerio.load(response.data); + $("._2n7i6c").each(function (el, index) { + const name = $(this).find("a._2rpwqI").attr("title"); + const price = $(this).find("div._30jeq3").text(); + const link = $(this).find("a.s1Q9rs").attr("href"); + const rating = $(this).find("div._3LWZlK").text(); + const discount = $(this).find("div._3Ay6Sb").text().split(" ")[0]; - movie.push({product_name:name, price:price, rating:rating, discount:discount, link:link}) + movie.push({ + product_name: name, + price: price, + rating: rating, + discount: discount, + link: link, + }); + }); }); - })}catch(error){ + } catch (error) { console.log(error); } - return movie + return movie; }; // Function to scrape the category page and get product URLs @@ -182,68 +193,74 @@ async function scrapeCategoryPage(categoryUrl) { const productUrls = []; const $ = Cheerio.load(response.data); - - $('a.s1Q9rs').each((index, element) => { - const productUrl = $(element).attr('href'); + + $("a.s1Q9rs").each((index, element) => { + const productUrl = $(element).attr("href"); productUrls.push(productUrl); console.log(productUrls); }); return productUrls; } catch (error) { - console.error('Error scraping category page:', error.message); + console.error("Error scraping category page:", error.message); throw error; } } -const flipkartAll = async ()=>{ - +const flipkartAll = async () => { const movie = []; - try{ - await axios.get(config.URL1) - .then((response)=>{ - let $ = Cheerio.load(response.data); - $('._2kHMtA').each(function(el, index){ - const name = ($(this).find('._4rR01T').text()); - const productUrl = ($(this).find('a._1fQZEK').attr('href')); + try { + await axios.get(config.URL1).then((response) => { + let $ = Cheerio.load(response.data); + $("._2kHMtA").each(function (el, index) { + const name = $(this).find("._4rR01T").text(); + const productUrl = $(this).find("a._1fQZEK").attr("href"); - movie.push({product_name:name,link:productUrl}) + movie.push({ product_name: name, link: productUrl }); + }); }); - })}catch(error){ + } catch (error) { console.log(error); } - return movie - + return movie; }; -const snapdeal = async ()=>{ - const Tshirt = [] - try{ - await axios.get(config.snapURL) - .then((response)=>{ - let $ = Cheerio.load(response.data); - $('.favDp.product-tuple-listing.js-tuple').each(function(el, index){ - const name = ($(this).find('p.product-title').attr('title')); - const price = ($(this).find('span.product-price').text()); - const link = ($(this).find('a.dp-widget-link').attr('href')); - const image = ($(this).find('img.product-image').attr('src')); - const discount = ($(this).find('.product-discount span').text().split(" ")[0]); - Tshirt.push({product_name:name, image:image, price:price, discount:discount, link:link}) - console.log(Tshirt); +const snapdeal = async () => { + const Tshirt = []; + try { + await axios.get(config.snapURL).then((response) => { + let $ = Cheerio.load(response.data); + $(".favDp.product-tuple-listing.js-tuple").each(function (el, index) { + const name = $(this).find("p.product-title").attr("title"); + const price = $(this).find("span.product-price").text(); + const link = $(this).find("a.dp-widget-link").attr("href"); + const image = $(this).find("img.product-image").attr("src"); + const discount = $(this) + .find(".product-discount span") + .text() + .split(" ")[0]; + Tshirt.push({ + product_name: name, + image: image, + price: price, + discount: discount, + link: link, + }); + console.log(Tshirt); + }); }); - })}catch(error){ + } catch (error) { console.log(error); } - return Tshirt + return Tshirt; }; -const findByAggregate = async ()=>{ - +const findByAggregate = async () => { //projection const data = await DummyData.aggregate([ - {$match: { country: 'Vietnam'}}, - {$project:{_id:0, name:1, email:1}} - ]) + { $match: { country: "Vietnam" } }, + { $project: { _id: 0, name: 1, email: 1 } }, + ]); - /* Skip & Sort Aggregate + /* Skip & Sort Aggregate const d = await DummyData.aggregate([ {$group: { _id: '$country'}}, {$sort: { _id:1 }} // 1 for ascending and 2 for descending @@ -253,22 +270,39 @@ const findByAggregate = async ()=>{ {$count:'total'} ]) */ - return data -} + return data; +}; -module.exports={ - getdata, - deleteuser, - updateuser1, - modifyPass, - matchpass, - verifyemail, - user_list, - userlogin, - usersignup, - useraddress, - flipkart, - flipkartAll, - snapdeal, - findByAggregate -} \ No newline at end of file +const generateToken = (RTemail) => { + // Correct token we send a new access token + userCredentials = User.findOne({where:{email:RTemail}}) + const accessToken = jwt.sign( + { + username: userCredentials.username, + email: userCredentials.email, + }, + process.env.ACCESS_TOKEN_SECRET, + { + expiresIn: "10m", + } + ); + return res.json({ accessToken }); +}; + +module.exports = { + getdata, + deleteuser, + updateuser1, + modifyPass, + matchpass, + verifyemail, + user_list, + userlogin, + usersignup, + useraddress, + flipkart, + flipkartAll, + snapdeal, + findByAggregate, + generateToken, +};