From 4404fc02429aa1d1be600919df50107165c00699 Mon Sep 17 00:00:00 2001 From: snyk-bot Date: Sat, 21 Sep 2024 03:26:47 +0000 Subject: [PATCH 01/18] fix: upgrade axios from 1.7.5 to 1.7.6 Snyk has created this PR to upgrade axios from 1.7.5 to 1.7.6. See this package in npm: axios See this project in Snyk: https://app.snyk.io/org/navodveduth/project/f24c42b7-23f1-4da6-adad-089c71ae16a3?utm_source=github&utm_medium=referral&page=upgrade-pr --- FrontEnd/package-lock.json | 14 +++++++------- FrontEnd/package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/FrontEnd/package-lock.json b/FrontEnd/package-lock.json index 39c503e..05dabf8 100644 --- a/FrontEnd/package-lock.json +++ b/FrontEnd/package-lock.json @@ -10,7 +10,7 @@ "dependencies": { "@popperjs/core": "^2.11.8", "@tinymce/tinymce-react": "^5.1.1", - "axios": "^1.7.5", + "axios": "^1.7.6", "chart.js": "^4.4.4", "dompurify": "^3.1.6", "react": "^18.3.1", @@ -5009,9 +5009,9 @@ } }, "node_modules/axios": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.5.tgz", - "integrity": "sha512-fZu86yCo+svH3uqJ/yTdQ0QHpQu5oL+/QE+QPSv6BZSkDAoky9vytxp7u5qk83OJFS3kEBcesWni9WTZAv3tSw==", + "version": "1.7.6", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.6.tgz", + "integrity": "sha512-Ekur6XDwhnJ5RgOCaxFnXyqlPALI3rVeukZMwOdfghW7/wGz784BYKiQq+QD8NPcr91KRo30KfHOchyijwWw7g==", "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", @@ -21070,9 +21070,9 @@ "integrity": "sha512-sCXXUhA+cljomZ3ZAwb8i1p3oOlkABzPy08ZDAoGcYuvtBPlQ1Ytde129ArXyHWDhfeewq7rlx9F+cUx2SSlkg==" }, "axios": { - "version": "1.7.5", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.5.tgz", - "integrity": "sha512-fZu86yCo+svH3uqJ/yTdQ0QHpQu5oL+/QE+QPSv6BZSkDAoky9vytxp7u5qk83OJFS3kEBcesWni9WTZAv3tSw==", + "version": "1.7.6", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.6.tgz", + "integrity": "sha512-Ekur6XDwhnJ5RgOCaxFnXyqlPALI3rVeukZMwOdfghW7/wGz784BYKiQq+QD8NPcr91KRo30KfHOchyijwWw7g==", "requires": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", diff --git a/FrontEnd/package.json b/FrontEnd/package.json index 85cd1f1..c22e051 100644 --- a/FrontEnd/package.json +++ b/FrontEnd/package.json @@ -13,7 +13,7 @@ "dependencies": { "@popperjs/core": "^2.11.8", "@tinymce/tinymce-react": "^5.1.1", - "axios": "^1.7.5", + "axios": "^1.7.6", "chart.js": "^4.4.4", "dompurify": "^3.1.6", "react": "^18.3.1", From 473a2f82fe0a1f50b4983d9f795458687e2395d9 Mon Sep 17 00:00:00 2001 From: snyk-bot Date: Sat, 21 Sep 2024 04:36:40 +0000 Subject: [PATCH 02/18] fix: upgrade nodemon from 3.0.0 to 3.1.4 Snyk has created this PR to upgrade nodemon from 3.0.0 to 3.1.4. See this package in npm: nodemon See this project in Snyk: https://app.snyk.io/org/navodveduth/project/7082bec9-4446-4f05-86ac-d8066d9217ff?utm_source=github&utm_medium=referral&page=upgrade-pr --- package-lock.json | 46 ++++++++++++++++++++++++++++------------------ package.json | 2 +- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1e7c592..fe12e44 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,7 +23,7 @@ "find-config": "^1.0.0", "jsonwebtoken": "^9.0.2", "mongoose": "^7.8.1", - "nodemon": "^3.0.0" + "nodemon": "^3.1.4" }, "devDependencies": { "jest": "^29.5.0", @@ -5177,13 +5177,13 @@ "license": "MIT" }, "node_modules/nodemon": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.0.0.tgz", - "integrity": "sha512-yU9NSp3n+DUSt3S2LmtXss+4kOsmC8ZLpXeGe5mKuLdqkoSRwmaplk2lo5cmve7TPw5MgMcd2cazL0KpUscoSQ==", + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.4.tgz", + "integrity": "sha512-wjPBbFhtpJwmIeY2yP7QF+UKzPfltVGtfce1g/bB15/8vCGZj8uxD62b/b9M9/WVgme0NZudpownKN+c0plXlQ==", "license": "MIT", "dependencies": { "chokidar": "^3.5.2", - "debug": "^3.2.7", + "debug": "^4", "ignore-by-default": "^1.0.1", "minimatch": "^3.1.2", "pstree.remy": "^1.1.8", @@ -5205,17 +5205,27 @@ } }, "node_modules/nodemon/node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", "dependencies": { - "ms": "^2.1.1" + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, "node_modules/nodemon/node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" }, "node_modules/nopt": { "version": "1.0.10", @@ -10177,12 +10187,12 @@ "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==" }, "nodemon": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.0.0.tgz", - "integrity": "sha512-yU9NSp3n+DUSt3S2LmtXss+4kOsmC8ZLpXeGe5mKuLdqkoSRwmaplk2lo5cmve7TPw5MgMcd2cazL0KpUscoSQ==", + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.4.tgz", + "integrity": "sha512-wjPBbFhtpJwmIeY2yP7QF+UKzPfltVGtfce1g/bB15/8vCGZj8uxD62b/b9M9/WVgme0NZudpownKN+c0plXlQ==", "requires": { "chokidar": "^3.5.2", - "debug": "^3.2.7", + "debug": "^4", "ignore-by-default": "^1.0.1", "minimatch": "^3.1.2", "pstree.remy": "^1.1.8", @@ -10194,11 +10204,11 @@ }, "dependencies": { "debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "requires": { - "ms": "^2.1.1" + "ms": "^2.1.3" } }, "ms": { diff --git a/package.json b/package.json index 88327ed..95e0e95 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "find-config": "^1.0.0", "jsonwebtoken": "^9.0.2", "mongoose": "^7.8.1", - "nodemon": "^3.0.0" + "nodemon": "^3.1.4" }, "devDependencies": { "jest": "^29.5.0", From 425a8f299cb7ae4ab215bf08a7b2c8e0d2a29ba1 Mon Sep 17 00:00:00 2001 From: Dinushkasam Date: Sat, 21 Sep 2024 17:39:09 +0530 Subject: [PATCH 03/18] Hard coded credentials --- BackEnd/tests/userController.test.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/BackEnd/tests/userController.test.js b/BackEnd/tests/userController.test.js index 6960aa5..5e0def3 100644 --- a/BackEnd/tests/userController.test.js +++ b/BackEnd/tests/userController.test.js @@ -11,6 +11,8 @@ dotenv.config({ path: findConfig('.env.dev') }); let authToken, adminToken; let userId, adminId; +const INVALID_TOKEN = 'Bearer invalidtoken'; + const testAdmin = { username: 'Benjamin', email: 'benjamin@gmail.com', @@ -108,7 +110,7 @@ describe('User Controller', () => { test('Return 401 unauthorized error when passed an invalid auth token - GET api/users/profile', async () => { const response = await request(app) .get('/api/users/profile') - .set('Authorization', 'Bearer invalidtoken') + .set('Authorization', INVALID_TOKEN) .expect(401); expect(response.body.message).toBe('Not authorized, token failed'); }); @@ -141,7 +143,7 @@ describe('User Controller', () => { const updateData = { username: 'newusername' }; const response = await request(app) .put('/api/users/profile') - .set('Authorization', 'Bearer invalidtoken') + .set('Authorization', INVALID_TOKEN) .send(updateData) .expect(401); expect(response.body.message).toBe('Not authorized, token failed'); From 3650302e34cd7e71045c58d7b9dcd95ac502615e Mon Sep 17 00:00:00 2001 From: Dinushkasam Date: Sat, 21 Sep 2024 18:15:03 +0530 Subject: [PATCH 04/18] misconfoguration - logger instead of stack trace --- BackEnd/config/db.js | 6 ++-- BackEnd/controllers/blogController.js | 6 ++-- BackEnd/controllers/cropController.js | 41 +++++++++++------------- BackEnd/controllers/diseaseController.js | 26 +++++++-------- BackEnd/controllers/logger.js | 41 ++++++++++++++++++++++++ BackEnd/index.js | 3 +- BackEnd/middleware/errorMiddleware.js | 5 +++ BackEnd/tests/blogController.test.js | 2 -- 8 files changed, 85 insertions(+), 45 deletions(-) create mode 100644 BackEnd/controllers/logger.js diff --git a/BackEnd/config/db.js b/BackEnd/config/db.js index ff1b3ee..4a15221 100644 --- a/BackEnd/config/db.js +++ b/BackEnd/config/db.js @@ -1,14 +1,16 @@ import mongoose from 'mongoose'; +import colors from 'colors'; +import logger from '../controllers/logger.js'; const connectDB = async () => { try { const conn = await mongoose.connect(process.env.MONGO_URI, {}); - console.log( + logger.info( `MongoDB database connection established successfully: ${conn.connection.host}` .cyan.underline ); } catch (error) { - console.log(`Error: ${error.message}`.red.underline.bold); + logger.error(`Error: ${error.message}`.red.underline.bold); process.exit(1); } }; diff --git a/BackEnd/controllers/blogController.js b/BackEnd/controllers/blogController.js index 227958c..14c0b7b 100644 --- a/BackEnd/controllers/blogController.js +++ b/BackEnd/controllers/blogController.js @@ -142,8 +142,8 @@ const searchBlogs = asyncHandler(async (req, res) => { }).populate('author', 'username firstName lastName'); res.json(blog); } catch (error) { - console.log(error); res.status(404).json({ message: 'Blog not found' }); + throw new Error(error.message); } }); @@ -272,8 +272,8 @@ const getBlogsByAuthor = asyncHandler(async (req, res) => { res.status(404).json({ message: 'No blogs found' }); } } catch (error) { - console.log(error); res.status(404).json({ message: 'Blog not found' }); + throw new Error(error.message); } }); @@ -319,8 +319,8 @@ const getLatestBlogs = asyncHandler(async (req, res) => { throw new Error('No blogs found'); } } catch (error) { - console.log(error); res.status(404).json({ message: 'No blogs found' }); + throw new Error(error.message); } }); diff --git a/BackEnd/controllers/cropController.js b/BackEnd/controllers/cropController.js index 29a1f5e..51ece59 100644 --- a/BackEnd/controllers/cropController.js +++ b/BackEnd/controllers/cropController.js @@ -9,8 +9,8 @@ const getCrops = asyncHandler(async (req, res) => { const crops = await Crop.find({}).populate('author', 'firstName lastName'); res.json(crops); } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -27,12 +27,11 @@ const getCropById = asyncHandler(async (req, res) => { throw new Error('Crop not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); - // @desc Fetch all accepted crops // @route GET /api/crops/accepted // @access Public @@ -41,14 +40,13 @@ const getAllAcceptedCrops = asyncHandler(async (req, res) => { const crops = await Crop.find({ isAccepted: true }); if (crops) { res.json(crops); - console.log('crops', crops); } else { res.status(404); throw new Error('Crops not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -65,8 +63,8 @@ const deleteCrop = asyncHandler(async (req, res) => { throw new Error('Crop not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -116,8 +114,8 @@ const createCrop = asyncHandler(async (req, res) => { res.status(201).json(createdCrop); } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -156,8 +154,8 @@ const updateCrop = asyncHandler(async (req, res) => { throw new Error('Crop not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -172,12 +170,12 @@ const searchCrops = asyncHandler(async (req, res) => { }); res.json(crops); } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); -//@desc Get latest 4 crops +//@desc Get latest 4 crops //@route GET /api/crops/short //@access Public const getShortCrops = asyncHandler(async (req, res) => { @@ -185,15 +183,13 @@ const getShortCrops = asyncHandler(async (req, res) => { const crops = await Crop.find({}).limit(4); if (crops) { res.json(crops); - } - else { + } else { res.status(404); throw new Error('Crops not found'); } - } - catch (error) { - console.log(error); + } catch (error) { res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -228,8 +224,8 @@ const getCropsByAuthor = asyncHandler(async (req, res) => { throw new Error('Crops not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -241,9 +237,10 @@ const addRemoveCropBookmark = asyncHandler(async (req, res) => { try { const crop = await Crop.findById(req.params.id); if (crop) { - if (crop.bookmarkedBy.filter( - (bookmark) => bookmark.toString() === req.body.userId.toString() - ).length > 0 + if ( + crop.bookmarkedBy.filter( + (bookmark) => bookmark.toString() === req.body.userId.toString() + ).length > 0 ) { crop.bookmarkedBy = crop.bookmarkedBy.filter( (bookmark) => bookmark.toString() !== req.body.userId.toString() @@ -258,13 +255,11 @@ const addRemoveCropBookmark = asyncHandler(async (req, res) => { throw new Error('Crop not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); - - const getCropBookmarksByUser = asyncHandler(async (req, res) => { try { const crops = await Crop.find({ bookmarkedBy: req.params.id }); @@ -275,8 +270,8 @@ const getCropBookmarksByUser = asyncHandler(async (req, res) => { throw new Error('Crops not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); diff --git a/BackEnd/controllers/diseaseController.js b/BackEnd/controllers/diseaseController.js index fb8beb9..9cca655 100644 --- a/BackEnd/controllers/diseaseController.js +++ b/BackEnd/controllers/diseaseController.js @@ -12,8 +12,8 @@ const getCropDiseases = asyncHandler(async (req, res) => { ); res.json(cropDiseases); } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -30,8 +30,8 @@ const getCropDiseaseById = asyncHandler(async (req, res) => { throw new Error('Crop disease not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -43,14 +43,13 @@ const getAllAcceptedCropDiseases = asyncHandler(async (req, res) => { const cropDiseases = await CropDisease.find({ isAccepted: true }); if (cropDiseases) { res.json(cropDiseases); - console.log('cropDiseases', cropDiseases); } else { res.status(404); throw new Error('Crop diseases not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -67,8 +66,8 @@ const deleteCropDisease = asyncHandler(async (req, res) => { throw new Error('Crop disease not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -117,8 +116,8 @@ const createCropDisease = asyncHandler(async (req, res) => { const createdCropDisease = await cropDisease.save(); res.status(201).json(createdCropDisease); } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -159,8 +158,8 @@ const updateCropDisease = asyncHandler(async (req, res) => { throw new Error('Crop disease not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -180,8 +179,8 @@ const searchCropDisease = asyncHandler(async (req, res) => { throw new Error('Crop disease not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -197,10 +196,9 @@ const getRandomCropDiseases = asyncHandler(async (req, res) => { res.status(404); throw new Error('Crop disease not found'); } - } - catch (error) { - console.log(error); + } catch (error) { res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -236,8 +234,8 @@ const getDiseasesByAuthor = asyncHandler(async (req, res) => { throw new Error('Diseases not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -267,8 +265,8 @@ const addRemoveDiseaseBookmark = asyncHandler(async (req, res) => { throw new Error('Disease not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); @@ -282,8 +280,8 @@ const getDiseaseBookmarksByUser = asyncHandler(async (req, res) => { throw new Error('Diseases not found'); } } catch (error) { - console.log(error); res.status(400).json({ message: error.message }); + throw new Error(error.message); } }); diff --git a/BackEnd/controllers/logger.js b/BackEnd/controllers/logger.js new file mode 100644 index 0000000..721047f --- /dev/null +++ b/BackEnd/controllers/logger.js @@ -0,0 +1,41 @@ +/** + * This file is used to log info to a file + * Three log levels exist: info, warning, error + */ + +import fs from 'fs'; +import path from 'path'; + +export const LOG = { + INFO: 'info', + WARNING: 'warning', + ERROR: 'error', +}; +const __dirname = path.resolve(); + +const log = (level, message) => { + const logMessage = `${new Date().toISOString()} [${level.toUpperCase()}]: ${message}\n`; + + const logPath = path.join(__dirname, '../logs'); + if (!fs.existsSync(logPath)) { + fs.mkdirSync(logPath); + } + + const logFile = path.join(logPath, `${level}.log`); + fs.appendFileSync(logFile, logMessage); + console.log(logMessage); +}; + +const info = (message) => { + log(LOG.INFO, message); +}; + +const warning = (message) => { + log(LOG.WARNING, message); +}; + +const error = (message) => { + log(LOG.ERROR, message); +}; + +export default { info, warning, error }; diff --git a/BackEnd/index.js b/BackEnd/index.js index 43cbe25..71463c6 100644 --- a/BackEnd/index.js +++ b/BackEnd/index.js @@ -17,6 +17,7 @@ import forumRoutes from './routes/forumRoutes.js'; import blogRoutes from './routes/blogRoutes.js'; import cropRoutes from './routes/cropRoutes.js'; import diseaseRoutes from './routes/diseaseRoutes.js'; +import logger from './controllers/logger.js'; if (process.env.NODE_ENV !== 'production') { dotenv.config({ path: findConfig('.env.dev') }); @@ -59,7 +60,7 @@ app.use(errorHandler); const PORT = process.env.PORT || 5000; if (process.env.NODE_ENV !== 'test') { app.listen(PORT, () => { - console.log(`Server is running on port: ${PORT}`.yellow.bold); + logger.info(`Server is running on port: ${PORT}`.yellow.bold); }); } diff --git a/BackEnd/middleware/errorMiddleware.js b/BackEnd/middleware/errorMiddleware.js index ead6082..dfc7fa0 100644 --- a/BackEnd/middleware/errorMiddleware.js +++ b/BackEnd/middleware/errorMiddleware.js @@ -1,3 +1,5 @@ +import logger from '../controllers/logger.js'; + // Custom error handling middleware to handle 404 and 500 errors const notFound = (req, res, next) => { const error = new Error(`Not Found - ${req.originalUrl}`); @@ -8,6 +10,9 @@ const notFound = (req, res, next) => { const errorHandler = (err, req, res, next) => { const statusCode = res.statusCode === 200 ? 500 : res.statusCode; res.status(statusCode); + logger.error( + `${statusCode} - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}` + ); res.json({ message: err.message, stack: process.env.NODE_ENV === 'production' ? null : err.stack, diff --git a/BackEnd/tests/blogController.test.js b/BackEnd/tests/blogController.test.js index d22a474..e38f05b 100644 --- a/BackEnd/tests/blogController.test.js +++ b/BackEnd/tests/blogController.test.js @@ -56,8 +56,6 @@ describe('Blog Controller', () => { if (res) { blogId._id = res.body._id; } - - console.log('blogID', blogId); }); test('Should get all blogs - GET /api/blog', async () => { From d0d9230d0414788e6a472c255781f538f7d26f45 Mon Sep 17 00:00:00 2001 From: Dinushkasam Date: Sat, 21 Sep 2024 18:27:47 +0530 Subject: [PATCH 05/18] remove stack trace prints --- FrontEnd/src/api/blog.js | 48 +- FrontEnd/src/api/forum.js | 4 +- FrontEnd/src/api/knowlegdebase.js | 65 +- FrontEnd/src/api/user.js | 20 +- FrontEnd/src/pages/blog/BlogCreate.jsx | 114 +-- FrontEnd/src/pages/blog/BlogDashboard.jsx | 65 +- FrontEnd/src/pages/blog/BlogSearch.jsx | 27 +- FrontEnd/src/pages/blog/BlogUpdate.jsx | 105 ++- FrontEnd/src/pages/blog/BlogView.jsx | 61 +- FrontEnd/src/pages/blog/BookmarkedBlogs.jsx | 33 +- FrontEnd/src/pages/blog/MyBlogPosts.jsx | 28 +- FrontEnd/src/pages/common/Home.jsx | 89 ++- FrontEnd/src/pages/common/Search.jsx | 19 +- .../src/pages/knowledgebase/CreateCrop.jsx | 401 ++++++----- .../src/pages/knowledgebase/CreateDisease.jsx | 292 ++++---- FrontEnd/src/pages/knowledgebase/Crop.jsx | 293 ++++---- FrontEnd/src/pages/knowledgebase/Disease.jsx | 431 ++++++------ .../src/pages/knowledgebase/MyArticles.jsx | 96 +-- .../src/pages/knowledgebase/UpdateCrop.jsx | 658 +++++++++--------- .../src/pages/knowledgebase/UpdateDisease.jsx | 272 ++++---- 20 files changed, 1637 insertions(+), 1484 deletions(-) diff --git a/FrontEnd/src/api/blog.js b/FrontEnd/src/api/blog.js index 0a02407..7ae7598 100644 --- a/FrontEnd/src/api/blog.js +++ b/FrontEnd/src/api/blog.js @@ -4,10 +4,9 @@ import axios from 'axios'; export const getAllBlogs = async () => { try { const response = await axios.get('/api/blog'); - console.log('blog', response.data); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -16,10 +15,9 @@ export const getAllBlogs = async () => { export const getBlogById = async (id) => { try { const response = await axios.get(`/api/blog/${id}`); - //console.log('blog', response.data); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -30,7 +28,7 @@ export const getAcceptedBlogs = async () => { const response = await axios.get('/api/blog'); return response.data.filter((blog) => blog.isAccepted); } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -41,7 +39,7 @@ export const createBlog = async (blog) => { const response = await axios.post('/api/blog', blog); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -50,10 +48,9 @@ export const createBlog = async (blog) => { export const updateBlog = async (id, blog) => { try { const response = await axios.put(`/api/blog/${id}`, blog); - console.log('blog', response.data); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -62,10 +59,9 @@ export const updateBlog = async (id, blog) => { export const deleteBlog = async (id) => { try { const response = await axios.delete(`/api/blog/${id}`); - console.log('blog', response.data); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -74,10 +70,9 @@ export const deleteBlog = async (id) => { export const searchBlog = async (keyword) => { try { const response = await axios.get(`/api/blog/search/q=${keyword}`); - console.log('blog', response); return response; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -86,10 +81,9 @@ export const searchBlog = async (keyword) => { export const commentonBlog = async (id, comment) => { try { const response = await axios.post(`/api/blog/comment/${id}`, comment); - console.log('blog', response.data); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -98,10 +92,9 @@ export const commentonBlog = async (id, comment) => { export const likeBlog = async (id, user) => { try { const response = await axios.post(`/api/blog/like/${id}`, { userId: user }); - console.log('blog', response.data); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -112,10 +105,9 @@ export const disLikeBlog = async (id, user) => { const response = await axios.post(`/api/blog/dislike/${id}`, { userId: user, }); - console.log('blog', response.data); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -126,7 +118,7 @@ export const updateBlogAccept = async (id, blog) => { const response = await axios.put(`/api/blog/${id}/accept`, blog); return response; } catch (error) { - console.log(error); + console.log('BLOG', error.message); } }; @@ -136,7 +128,7 @@ export const getBlogsByAuthor = async (authorId) => { const response = await axios.get(`/api/blog/author/${authorId}`); return response.data.filter((blog) => blog.isAccepted); } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -147,7 +139,7 @@ export const blogCommentAccept = async (id, blog) => { const response = await axios.put(`/api/blog/${id}/comment`, blog); return response; } catch (error) { - console.log(error); + console.log('BLOG', error.message); } }; @@ -157,7 +149,7 @@ export const deleteBlogComment = async (id, commentId) => { const response = await axios.delete(`/api/blog/comment/${id}/${commentId}`); return response; } catch (error) { - console.log(error); + console.log('BLOG', error.message); } }; @@ -167,10 +159,9 @@ export const handleBlogBookamrk = async (id, user) => { const response = await axios.post(`/api/blog/bookmark/${id}`, { userId: user, }); - console.log('blog', response.data); return response; } catch (error) { - console.log(error); + console.log('BLOG', error.message); } }; @@ -180,19 +171,18 @@ export const getBookmarkedBlogs = async (userId) => { const response = await axios.get(`/api/blog/bookmark/${userId}`); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; - //get latest four blogPosts export const getLatestBlogPosts = async () => { try { const response = await axios.get('/api/blog/new'); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } }; @@ -203,7 +193,7 @@ export const getAuthorAllBlogs = async (authorId) => { const response = await axios.get(`/api/blog/author/${authorId}`); return response.data; } catch (error) { - console.log(error); + console.log('BLOG', error.message); return []; } -}; \ No newline at end of file +}; diff --git a/FrontEnd/src/api/forum.js b/FrontEnd/src/api/forum.js index 93e8d83..ba4cb7e 100644 --- a/FrontEnd/src/api/forum.js +++ b/FrontEnd/src/api/forum.js @@ -205,7 +205,7 @@ export const getSubscribedForumsByUser = async (user, checkStatus) => { return null; } } catch (error) { - //console.log(error); + //ignore error } }; @@ -478,7 +478,7 @@ export const getForumsByUser = async (user, checkStatus) => { return null; } } catch (error) { - //console.log(error.message); + //ignore error } }; diff --git a/FrontEnd/src/api/knowlegdebase.js b/FrontEnd/src/api/knowlegdebase.js index 4416ca8..273f911 100644 --- a/FrontEnd/src/api/knowlegdebase.js +++ b/FrontEnd/src/api/knowlegdebase.js @@ -4,10 +4,9 @@ import axios from 'axios'; export const getAllCrops = async () => { try { const response = await axios.get('/api/crops'); - console.log('crop', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -16,10 +15,9 @@ export const getAllCrops = async () => { export const getAllCropsShort = async () => { try { const response = await axios.get('/api/crops/short'); - console.log('crop', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -28,10 +26,9 @@ export const getAllCropsShort = async () => { export const getCropById = async (id) => { try { const response = await axios.get(`/api/crops/${id}`); - console.log('crop', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -48,7 +45,7 @@ export const createCrop = async (crop, token) => { const response = await axios.post('/api/crops', crop, config); return response; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); } }; @@ -62,10 +59,9 @@ export const updateCrop = async (id, crop, token) => { try { const response = await axios.put(`/api/crops/${id}`, crop, config); - console.log('crop', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -80,10 +76,9 @@ export const deleteCrop = async (id, token) => { try { const response = await axios.delete(`/api/crops/${id}`, config); - console.log('crop', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -95,7 +90,7 @@ export const searchCrop = async (name) => { return response; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -112,7 +107,7 @@ export const updateCropAccept = async (id, crop, token) => { const response = await axios.put(`/api/crops/${id}/accept`, crop, config); return response; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); } }; @@ -120,10 +115,9 @@ export const updateCropAccept = async (id, crop, token) => { export const getCropsByAuthor = async (id) => { try { const response = await axios.get('/api/crops/author/' + id); - console.log('crop', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -132,10 +126,9 @@ export const getCropsByAuthor = async (id) => { export const getAllDiseases = async () => { try { const response = await axios.get('/api/diseases'); - console.log('disease', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -144,10 +137,9 @@ export const getAllDiseases = async () => { export const getRandomDiseases = async () => { try { const response = await axios.get('/api/diseases/random'); - console.log('disease', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -156,10 +148,9 @@ export const getRandomDiseases = async () => { export const getDiseaseById = async (id) => { try { const response = await axios.get(`/api/diseases/${id}`); - console.log('disease', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -174,10 +165,9 @@ export const createDisease = async (disease, token) => { try { const response = await axios.post('/api/diseases', disease, config); - console.log('disease', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -192,10 +182,9 @@ export const updateDisease = async (id, disease, token) => { try { const response = await axios.put(`/api/diseases/${id}`, disease, config); - console.log('disease', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -210,10 +199,9 @@ export const deleteDisease = async (id, token) => { try { const response = await axios.delete(`/api/diseases/${id}`, config); - console.log('disease', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -224,7 +212,7 @@ export const searchDisease = async (name) => { const response = await axios.get(`/api/diseases/search/q=${name}`); return response; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -245,7 +233,7 @@ export const updateDiseaseAccept = async (id, crop, token) => { ); return response; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); } }; @@ -253,10 +241,9 @@ export const updateDiseaseAccept = async (id, crop, token) => { export const getDiseasesByAuthor = async (id) => { try { const response = await axios.get('/api/diseases/author/' + id); - console.log('disease', response.data); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -266,7 +253,7 @@ export const addRemoveCropBookmarks = async (id, userId) => { const response = await axios.put(`/api/crops/bookmark/${id}`, { userId }); return response; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); } }; @@ -277,7 +264,7 @@ export const addRemoveDiseaseBookmarks = async (id, userId) => { }); return response; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); } }; @@ -286,7 +273,7 @@ export const getCropBookmarksByUser = async (id) => { const response = await axios.get(`/api/crops/bookmarks/${id}`); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -296,7 +283,7 @@ export const getDiseaseBookmarksByUser = async (id) => { const response = await axios.get('/api/diseases/bookmarks/' + id); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } }; @@ -306,17 +293,17 @@ export const getAllAcceptedCrops = async () => { const response = await axios.get('/api/crops/accepted'); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } -} +}; export const getAllAcceptedDiseases = async () => { try { const response = await axios.get('/api/diseases/accepted'); return response.data; } catch (error) { - console.log(error); + console.log('KNOWLEDGEBASE', error.message); return []; } -} \ No newline at end of file +}; diff --git a/FrontEnd/src/api/user.js b/FrontEnd/src/api/user.js index 3ff47a3..d6f4ac1 100644 --- a/FrontEnd/src/api/user.js +++ b/FrontEnd/src/api/user.js @@ -10,7 +10,7 @@ export const login = async (email, password) => { localStorage.setItem('userInfo', JSON.stringify(response.data)); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -33,7 +33,7 @@ export const register = async ( localStorage.setItem('userInfo', JSON.stringify(response.data)); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -55,7 +55,7 @@ export const getUsers = async (token) => { const response = await axios.get('/api/users', config); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -71,7 +71,7 @@ export const getUserDetails = async (id, token) => { const response = await axios.get(`/api/users/${id}`, config); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -89,7 +89,7 @@ export const updateProfile = async (user, token) => { localStorage.setItem('userInfo', JSON.stringify(response.data)); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -105,7 +105,7 @@ export const updateUser = async (user, token) => { const response = await axios.put(`/api/users/${user._id}`, user, config); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -125,7 +125,7 @@ export const requestRole = async (user, token) => { ); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -140,7 +140,7 @@ export const deleteUser = async (id, token) => { const response = await axios.delete(`/api/users/${id}`, config); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -156,7 +156,7 @@ export const getSiteVisits = async (token) => { const response = await axios.get('/api/visits', config); return response; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; @@ -166,6 +166,6 @@ export const getAuthorInfo = async (id, token) => { const response = await axios.get(`/api/users/${id}/author`); return response.data; } catch (error) { - console.log(error); + console.log('USER', error.message); } }; diff --git a/FrontEnd/src/pages/blog/BlogCreate.jsx b/FrontEnd/src/pages/blog/BlogCreate.jsx index 918ae63..19f200b 100644 --- a/FrontEnd/src/pages/blog/BlogCreate.jsx +++ b/FrontEnd/src/pages/blog/BlogCreate.jsx @@ -1,27 +1,27 @@ /** @format */ -import React from "react"; -import { useState, useEffect } from "react"; -import { useNavigate } from "react-router-dom"; -import { FaPenNib } from "react-icons/fa"; -import { BlogContainer, Loader } from "../../components"; -import { Editor } from "@tinymce/tinymce-react"; -import { useGlobalContext } from "../../context/ContextProvider"; -import { createBlog } from "../../api/blog"; -import { toast } from "react-toastify"; +import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { FaPenNib } from 'react-icons/fa'; +import { BlogContainer, Loader } from '../../components'; +import { Editor } from '@tinymce/tinymce-react'; +import { useGlobalContext } from '../../context/ContextProvider'; +import { createBlog } from '../../api/blog'; +import { toast } from 'react-toastify'; export default function BlogCreate() { //const { user } = useGlobalContext(); - const user = JSON.parse(localStorage.getItem("userInfo")); + const user = JSON.parse(localStorage.getItem('userInfo')); const authorID = user._id; const isLogged = user; // Check if user exists const [blog, setBlog] = useState({ - title: "", - body: "", - tags: "", + title: '', + body: '', + tags: '', author: authorID, }); @@ -41,7 +41,7 @@ export default function BlogCreate() { e.preventDefault(); try { const newBlog = await createBlog(blog); - toast.success("Blog Uploaded!", { + toast.success('Blog Uploaded!', { hideProgressBar: false, closeOnClick: true, autoClose: 1500, @@ -53,13 +53,13 @@ export default function BlogCreate() { navigateTo(`/viewblog/${newBlog._id}`); }, 2000); } catch (error) { - console.log("error", error); + console.log('error', error.message); } }; useEffect(() => { if (!user || !isLogged) { - window.location.href = "/login"; + window.location.href = '/login'; } }, [isLogged, user]); @@ -68,50 +68,57 @@ export default function BlogCreate() { {!isLogged ? ( ) : ( -
+
-
- - +
+ + Drafting as - {user.firstName} {user.lastName} ({user.username}) + + {' '} + {user.firstName} {user.lastName} ({user.username}) +
-
+
-
-
- + +
+
-
- +
+
-
- +
+
-
+
)} diff --git a/FrontEnd/src/pages/blog/BlogDashboard.jsx b/FrontEnd/src/pages/blog/BlogDashboard.jsx index 18dc818..b607710 100644 --- a/FrontEnd/src/pages/blog/BlogDashboard.jsx +++ b/FrontEnd/src/pages/blog/BlogDashboard.jsx @@ -1,25 +1,25 @@ /** @format */ -import React from "react"; -import { useState, useEffect } from "react"; -import { getAllBlogs, getAcceptedBlogs } from "../../api/blog"; +import React from 'react'; +import { useState, useEffect } from 'react'; +import { getAllBlogs, getAcceptedBlogs } from '../../api/blog'; import { BlogContainer, BlogBanner, PublicBlogCard, BlogSearchBar, Loader, -} from "../../components"; -import { Link } from "react-router-dom"; +} from '../../components'; +import { Link } from 'react-router-dom'; export default function BlogDashboard() { const [blogs, setBlogs] = useState([]); const [isLogged, setIsLogged] = useState(false); const [loading, setLoading] = useState(true); - const user = JSON.parse(localStorage.getItem("userInfo")); + const user = JSON.parse(localStorage.getItem('userInfo')); - let userID = ""; + let userID = ''; if (user && blogs) { userID = user._id; @@ -32,7 +32,7 @@ export default function BlogDashboard() { const blogs = await getAcceptedBlogs(); setBlogs(blogs); } catch (error) { - console.log("error", error); + console.log('error', error.message); } setLoading(false); }; @@ -48,50 +48,50 @@ export default function BlogDashboard() { return (
{loading ? ( -
+
) : (
{/* */} -
-

+
+

Blog Dashboard

-

+

Everything about Agriculture

-
+
-
-
+
+
{isLogged ? ( -
    -
  • - -
    +
      +
    • + +
      Featured Blog Posts
    • -
    • - -
      +
    • + +
      Start Your Blog
    • -
    • +
    • -
      +
      My Blogs
    • -
    • +
    • -
      +
      Bookmarks
      @@ -99,30 +99,29 @@ export default function BlogDashboard() {
    ) : (
    - +
    )}
    -
    +
    -
    +
    {blogs.map((blog) => (
    { const { searchTerm } = useParams(); @@ -18,14 +18,13 @@ const BlogSearch = () => { setIsLoading(false); }) .catch((error) => { - console.log(error); + console.log('BLOG', error.message); }); }, [searchTerm]); - console.log(searchResults); if (isLoading) { return ( -
    +
    ); @@ -34,20 +33,20 @@ const BlogSearch = () => { return (
    -
    -
    -

    +
    +
    +

    Search Results for : {searchTerm}

    -
    +
    -
    +
    {searchResults.map((blog) => ( -
    +
    { @@ -30,11 +30,10 @@ export default function BlogUpdate() { const fetchBlog = async () => { const blog = await getBlogById(id); setBlog(blog); - //console.log(blog); }; fetchBlog(); } catch (error) { - console.log("error", error); + console.log('error', error.message); } }, [id]); @@ -44,7 +43,6 @@ export default function BlogUpdate() { setBody(blog.body); setTags(blog.tags); setAuthor(blog.author); - //console.log(title); } }, [blog]); @@ -66,7 +64,7 @@ export default function BlogUpdate() { try { const result = await updateBlog(id, updatedBlog); - toast.success("Blog updated", { + toast.success('Blog updated', { hideProgressBar: false, closeOnClick: true, autoClose: 1500, @@ -78,57 +76,57 @@ export default function BlogUpdate() { navigateTo(`/viewblog/${id}`); }, 1000); } catch (error) { - console.log("error", error); + console.log('error', error.message); } }; return ( -
    +
    -
    - - +
    + + Drafting as {user.username}
    -
    -
    -