From 80585026b6d92fb7d1dec184c3484c536c4189ac Mon Sep 17 00:00:00 2001 From: balaharisankar Date: Sun, 28 Jul 2024 20:05:11 +0530 Subject: [PATCH] Bug: Reset password fixed --- backend/.env | 1 + backend/app.js | 2 +- .../Q&A/answers/@validationSchema/index.js | 6 +- .../app/routes/Q&A/answers/deleteAnswer.js | 2 +- backend/app/routes/Q&A/answers/index.js | 2 +- .../routes/Q&A/answers/updateAnswerStatus.js | 74 ++++---- .../Q&A/question/@validationSchema/index.js | 4 +- .../app/routes/Q&A/question/deleteQuestion.js | 2 +- backend/app/routes/Q&A/question/index.js | 4 +- .../Q&A/question/updateQuestionStatus.js | 74 ++++---- .../routes/admin/@validationSchema/index.js | 18 +- backend/app/routes/admin/deleteAdmin.js | 68 +++---- backend/app/routes/admin/forgotPassword.js | 40 ++++- backend/app/routes/admin/getAdmins.js | 2 +- backend/app/routes/admin/index.js | 6 +- backend/app/routes/admin/resetPassword.js | 3 +- backend/app/routes/admin/updateAdmin.js | 56 +++--- .../broadcast/@validationSchema/index.js | 7 +- backend/app/routes/broadcast/index.js | 6 +- .../app/routes/broadcast/updateBroadcast.js | 86 ++++----- backend/app/routes/contactUs/delete.js | 4 +- backend/app/routes/faq/index.js | 7 +- backend/app/routes/faq/post.js | 5 +- backend/app/routes/faq/updateFaq.js | 41 +++-- backend/app/routes/index.js | 2 +- backend/app/routes/joinUs/deleteJoinUs.js | 24 ++- backend/app/routes/joinUs/index.js | 6 +- backend/app/routes/joinUs/post.js | 4 +- .../resources/@validationSchema/index.js | 2 +- backend/app/routes/resources/postResource.js | 2 +- .../app/routes/teamMember/deleteTeamMember.js | 6 +- .../routes/teamMember/getTeamMemberById.js | 7 +- .../app/routes/teamMember/getTeamMembers.js | 5 +- backend/app/routes/teamMember/index.js | 4 +- .../app/routes/teamMember/updateTeamMember.js | 51 +++--- backend/app/routes/testimonial/index.js | 2 - backend/config/index.js | 1 + backend/helpers/middlewares/cookie.js | 3 +- backend/index.js | 5 +- backend/package.json | 2 +- backend/tests/routes/FAQ/updateFaq.test.js | 19 +- .../routes/Q&A/updateAnswerStatus.test.js | 88 +++++----- .../routes/Q&A/updateQuestionStatus.test.js | 64 +++---- .../tests/routes/admin/deleteAdmin.test.js | 160 ++++++++--------- .../routes/broadcast/updateBroadcast.test.js | 146 +++++++-------- .../tests/routes/joinUs/deleteJoinUs.test.js | 86 ++++----- .../routes/teamMember/deleteTeamMember.js | 133 +++++++------- .../teamMember/updateTeamMember.test.js | 166 +++++++++--------- backend/utility/emailTemplates.js | 12 ++ frontend/package-lock.json | 5 + .../pages/ForgotPassword/ForgotPassword.jsx | 36 +++- .../ForgotPasswordRecovery.jsx | 41 ++++- 52 files changed, 854 insertions(+), 748 deletions(-) diff --git a/backend/.env b/backend/.env index b2ab43ac..0698bc84 100644 --- a/backend/.env +++ b/backend/.env @@ -8,3 +8,4 @@ EMAIL_HOST=smtp.gmail.com CLUSTER=no JWT_RESET_PASSWORD_EXPIRES_IN=1h LOCAL_DEV_ENV=http://localhost:3500/ +FRONTEND_URL=https://hitk-tech-community.netlify.app/ \ No newline at end of file diff --git a/backend/app.js b/backend/app.js index 2c6a34c5..1035b3f3 100644 --- a/backend/app.js +++ b/backend/app.js @@ -2,9 +2,9 @@ const express = require('express'); const cors = require('cors'); const helmet = require('helmet'); const responseTime = require('response-time'); +const cookieParser = require('cookie-parser'); const routes = require('./app/routes'); const { errorHandler } = require('./helpers/error'); -const cookieParser = require('cookie-parser'); require('colors'); require('./helpers/dbConnection'); diff --git a/backend/app/routes/Q&A/answers/@validationSchema/index.js b/backend/app/routes/Q&A/answers/@validationSchema/index.js index 51098c62..df1b80ac 100644 --- a/backend/app/routes/Q&A/answers/@validationSchema/index.js +++ b/backend/app/routes/Q&A/answers/@validationSchema/index.js @@ -12,12 +12,12 @@ const getAnswerValidationSchema = Joi.object().keys({ }); const updateAnswerStatusSchema = Joi.object().keys({ - id : Joi.string().min(24).max(24).required(), - status : Joi.boolean().required() + id: Joi.string().min(24).max(24).required(), + status: Joi.boolean().required(), }); module.exports = { answerValidationSchema, getAnswerValidationSchema, - updateAnswerStatusSchema + updateAnswerStatusSchema, }; diff --git a/backend/app/routes/Q&A/answers/deleteAnswer.js b/backend/app/routes/Q&A/answers/deleteAnswer.js index 96a2469a..bd07fe4e 100644 --- a/backend/app/routes/Q&A/answers/deleteAnswer.js +++ b/backend/app/routes/Q&A/answers/deleteAnswer.js @@ -1,7 +1,7 @@ const mongoose = require('mongoose'); const Answer = require('../../../models/answers'); -module.exports = async (req, res, next) => { +module.exports = async (req, res) => { try { const payload = res.locals.decode; const { answerId } = req.body; diff --git a/backend/app/routes/Q&A/answers/index.js b/backend/app/routes/Q&A/answers/index.js index 86ea6772..9df65a70 100644 --- a/backend/app/routes/Q&A/answers/index.js +++ b/backend/app/routes/Q&A/answers/index.js @@ -1,5 +1,5 @@ const router = require('express').Router({ mergeParams: true }); -const { answerValidationSchema, getAnswerValidationSchema, updateAnswerStatusSchema } = require('./@validationSchema'); +const { answerValidationSchema, updateAnswerStatusSchema } = require('./@validationSchema'); const validation = require('../../../../helpers/middlewares/validation'); const postAnswer = require('./post'); diff --git a/backend/app/routes/Q&A/answers/updateAnswerStatus.js b/backend/app/routes/Q&A/answers/updateAnswerStatus.js index 7822a123..26826f22 100644 --- a/backend/app/routes/Q&A/answers/updateAnswerStatus.js +++ b/backend/app/routes/Q&A/answers/updateAnswerStatus.js @@ -1,43 +1,43 @@ -const to = require("await-to-js").default; +const to = require('await-to-js').default; -const constants = require("../../../../constants"); -const { ErrorHandler } = require("../../../../helpers/error"); +const constants = require('../../../../constants'); +const { ErrorHandler } = require('../../../../helpers/error'); -const answers = require("../../../models/answers"); +const answers = require('../../../models/answers'); module.exports = async (req, res, next) => { - // getting id and status from body - const id = req.body.id; - const status = req.body.status - - // query fro updating - const [ err, result ] = await to(answers.findOneAndUpdate({ _id : id }, { $set : { isApproved : status } })); - - // error occured due to the some problem - if(err) { - const error = new ErrorHandler(constants.ERRORS.DATABASE, { - statusCode: 500, - message: 'Database Error', - errStack: err, - }); - - return next(error); - } - - // if result is null that means answer with given id is not exist in collection - if(result === null) { - const answerNotExistError = new ErrorHandler(constants.ERRORS.INPUT, { - statusCode: 400, - message: 'Answer Not Exist...', - }); - - return next(answerNotExistError); - } - - // success response - res.status(200).send({ - message : "Status Updated..." + // getting id and status from body + const { id } = req.body; + const { status } = req.body; + + // query fro updating + const [err, result] = await to(answers.findOneAndUpdate({ _id: id }, { $set: { isApproved: status } })); + + // error occured due to the some problem + if (err) { + const error = new ErrorHandler(constants.ERRORS.DATABASE, { + statusCode: 500, + message: 'Database Error', + errStack: err, }); - return next(); -} \ No newline at end of file + return next(error); + } + + // if result is null that means answer with given id is not exist in collection + if (result === null) { + const answerNotExistError = new ErrorHandler(constants.ERRORS.INPUT, { + statusCode: 400, + message: 'Answer Not Exist...', + }); + + return next(answerNotExistError); + } + + // success response + res.status(200).send({ + message: 'Status Updated...', + }); + + return next(); +}; diff --git a/backend/app/routes/Q&A/question/@validationSchema/index.js b/backend/app/routes/Q&A/question/@validationSchema/index.js index 10bfee90..46a8b375 100644 --- a/backend/app/routes/Q&A/question/@validationSchema/index.js +++ b/backend/app/routes/Q&A/question/@validationSchema/index.js @@ -7,8 +7,8 @@ const QuestionValidationSchema = Joi.object().keys({ }); const updateQuestionStatusSchema = Joi.object().keys({ - id : Joi.string().min(24).max(24).required(), - status : Joi.boolean().required() + id: Joi.string().min(24).max(24).required(), + status: Joi.boolean().required(), }); module.exports = { QuestionValidationSchema, updateQuestionStatusSchema }; diff --git a/backend/app/routes/Q&A/question/deleteQuestion.js b/backend/app/routes/Q&A/question/deleteQuestion.js index e8d21190..dc150bef 100644 --- a/backend/app/routes/Q&A/question/deleteQuestion.js +++ b/backend/app/routes/Q&A/question/deleteQuestion.js @@ -2,7 +2,7 @@ const mongoose = require('mongoose'); const Question = require('../../../models/question'); const Answer = require('../../../models/answers'); -module.exports = async (req, res, next) => { +module.exports = async (req, res) => { try { const payload = res.locals.decode; const { questionId } = req.body; diff --git a/backend/app/routes/Q&A/question/index.js b/backend/app/routes/Q&A/question/index.js index 19df08db..c97d07c8 100644 --- a/backend/app/routes/Q&A/question/index.js +++ b/backend/app/routes/Q&A/question/index.js @@ -20,10 +20,10 @@ router.get('/getallquestions', getAllQuestion); router.get('/getQuestionById/:questionId', getQuestionById); // This route will increase upvote by one. -router.patch('/upvote',checkVoteCookie, upvoteQuestion); +router.patch('/upvote', checkVoteCookie, upvoteQuestion); // This route will decrease upvote by one. -router.patch('/downvote',checkVoteCookie, downvoteQuestion); +router.patch('/downvote', checkVoteCookie, downvoteQuestion); // route for updating the question status router.patch('/updateStatus', validation(updateQuestionStatusSchema), updateQuestionStatus); diff --git a/backend/app/routes/Q&A/question/updateQuestionStatus.js b/backend/app/routes/Q&A/question/updateQuestionStatus.js index 97700534..35a99d9e 100644 --- a/backend/app/routes/Q&A/question/updateQuestionStatus.js +++ b/backend/app/routes/Q&A/question/updateQuestionStatus.js @@ -1,43 +1,43 @@ -const to = require("await-to-js").default; +const to = require('await-to-js').default; -const constants = require("../../../../constants"); -const { ErrorHandler } = require("../../../../helpers/error"); +const constants = require('../../../../constants'); +const { ErrorHandler } = require('../../../../helpers/error'); -const question = require("../../../models/question"); +const question = require('../../../models/question'); module.exports = async (req, res, next) => { - // getting id and status from body - const id = req.body.id; - const status = req.body.status - - // query fro updating - const [ err, result ] = await to(question.findOneAndUpdate({ _id : id }, { $set : { isApproved : status } })); - - // error occured due to the some problem - if(err) { - const error = new ErrorHandler(constants.ERRORS.DATABASE, { - statusCode: 500, - message: 'Database Error', - errStack: err, - }); - - return next(error); - } - - // if result is null that means question with given id is not exist in collection - if(result === null) { - const questionNotExistsError = new ErrorHandler(constants.ERRORS.INPUT, { - statusCode: 400, - message: 'Question Not Exist...', - }); - - return next(questionNotExistsError); - } - - // success response - res.status(200).send({ - message : "Status Updated..." + // getting id and status from body + const { id } = req.body; + const { status } = req.body; + + // query fro updating + const [err, result] = await to(question.findOneAndUpdate({ _id: id }, { $set: { isApproved: status } })); + + // error occured due to the some problem + if (err) { + const error = new ErrorHandler(constants.ERRORS.DATABASE, { + statusCode: 500, + message: 'Database Error', + errStack: err, }); - return next(); -} \ No newline at end of file + return next(error); + } + + // if result is null that means question with given id is not exist in collection + if (result === null) { + const questionNotExistsError = new ErrorHandler(constants.ERRORS.INPUT, { + statusCode: 400, + message: 'Question Not Exist...', + }); + + return next(questionNotExistsError); + } + + // success response + res.status(200).send({ + message: 'Status Updated...', + }); + + return next(); +}; diff --git a/backend/app/routes/admin/@validationSchema/index.js b/backend/app/routes/admin/@validationSchema/index.js index 02529547..6dc278c4 100644 --- a/backend/app/routes/admin/@validationSchema/index.js +++ b/backend/app/routes/admin/@validationSchema/index.js @@ -43,16 +43,16 @@ const forgotPasswordSchema = Joi.object({ const resetPasswordSchema = Joi.object({ newPassword: Joi.string().required(), }); -const updateAdminSchema =Joi.object({ - firstName:Joi.string(), - lastName:Joi.string(), - contact:Joi.string().regex(/[+]91[6-9]{1}[0-9]{9}$/, 'phone'), - username:Joi.string(), +const updateAdminSchema = Joi.object({ + firstName: Joi.string(), + lastName: Joi.string(), + contact: Joi.string().regex(/[+]91[6-9]{1}[0-9]{9}$/, 'phone'), + username: Joi.string(), }); const deleteAdminSchema = Joi.object({ - id : Joi.string().min(24).max(24).required() -}) + id: Joi.string().min(24).max(24).required(), +}); module.exports = { postSuperAdminSchema, @@ -62,5 +62,5 @@ module.exports = { forgotPasswordSchema, resetPasswordSchema, updateAdminSchema, - deleteAdminSchema -}; \ No newline at end of file + deleteAdminSchema, +}; diff --git a/backend/app/routes/admin/deleteAdmin.js b/backend/app/routes/admin/deleteAdmin.js index cbab67aa..2d44ae2b 100644 --- a/backend/app/routes/admin/deleteAdmin.js +++ b/backend/app/routes/admin/deleteAdmin.js @@ -1,45 +1,45 @@ -const { default: to } = require("await-to-js"); -const constants = require("../../../constants"); -const { ErrorHandler } = require("../../../helpers/error"); -const Admin = require("../../models/Admin"); +const { default: to } = require('await-to-js'); +const constants = require('../../../constants'); +const { ErrorHandler } = require('../../../helpers/error'); +const Admin = require('../../models/Admin'); module.exports = async (req, res, next) => { - const { isSuperAdmin } = res.locals.decode; + const { isSuperAdmin } = res.locals.decode; - if(!isSuperAdmin) { - const error = new ErrorHandler(constants.ERRORS.INPUT, { - statusCode: 401, - message: 'Unauthorized Request: Not a superAdmin', - user: req.body.email, - }); + if (!isSuperAdmin) { + const error = new ErrorHandler(constants.ERRORS.INPUT, { + statusCode: 401, + message: 'Unauthorized Request: Not a superAdmin', + user: req.body.email, + }); - return next(error); - } + return next(error); + } - const id = req.body.id; + const { id } = req.body; - const [err, admin] = await to(Admin.findByIdAndDelete(id)); + const [err, admin] = await to(Admin.findByIdAndDelete(id)); - if (!admin) { - const error = new ErrorHandler(constants.ERRORS.INPUT, { - statusCode: 400, - message: "Admin doesn't exist", - }); + if (!admin) { + const error = new ErrorHandler(constants.ERRORS.INPUT, { + statusCode: 400, + message: "Admin doesn't exist", + }); - return next(error); - } + return next(error); + } - if (err) { - const error = new ErrorHandler(constants.ERRORS.DATABASE, { - statusCode: 500, - message: 'Mongo Error: Deletion Failed', - errStack: err, - }); + if (err) { + const error = new ErrorHandler(constants.ERRORS.DATABASE, { + statusCode: 500, + message: 'Mongo Error: Deletion Failed', + errStack: err, + }); - return next(error); - } + return next(error); + } - return res.status(200).send({ - message: 'Admin deleted successfully', - }); -} \ No newline at end of file + return res.status(200).send({ + message: 'Admin deleted successfully', + }); +}; diff --git a/backend/app/routes/admin/forgotPassword.js b/backend/app/routes/admin/forgotPassword.js index a3e8c04f..6e12c5d0 100644 --- a/backend/app/routes/admin/forgotPassword.js +++ b/backend/app/routes/admin/forgotPassword.js @@ -1,11 +1,25 @@ +const nodemailer = require('nodemailer'); const Admin = require('../../models/Admin'); const config = require('../../../config'); const { ErrorHandler } = require('../../../helpers/error'); const constants = require('../../../constants'); const { generateJWT } = require('../../../helpers/middlewares/auth'); +const { resetPasswordMailTemplate } = require('../../../utility/emailTemplates'); + module.exports = async (req, res, next) => { const { email } = req.body; + const transporter = nodemailer.createTransport({ + type: 'SMTP', + host: config.EMAIL_HOST, + secure: true, + debug: true, + port: 465, + auth: { + user: config.EMAIL_USER, + pass: config.EMAIL_PASS, + }, + }); const userRecord = await Admin.findOne({ email }); if (!userRecord) { const error = new ErrorHandler(constants.ERRORS.INPUT, { @@ -17,14 +31,34 @@ module.exports = async (req, res, next) => { next(error); return false; } - // Setting EMAIL as the token payload const JWTPayload = { email }; const token = await generateJWT(JWTPayload, constants.JWT_RESET_PASSWORD_EXPIRES_IN); - + const data = { + adminName: `${userRecord.firstName} ${userRecord.lastName}`, + url: `${config.FRONTEND_URL}/forgot-password/${token}`, + }; + const mailOptions = { + from: `HITK TECH Community <${config.EMAIL_USER}>`, + to: email, + subject: 'Reset Password | HITK TECH Community', + html: resetPasswordMailTemplate(data), + }; + await transporter.sendMail(mailOptions).catch((err) => { + if (err) { + const error = new ErrorHandler(constants.ERRORS.UNEXPECTED, { + statusCode: 500, + message: 'The server encountered an unexpected condition which prevented it from fulfilling the request.', + errStack: err, + user: email, + }); + throw error; + } + }); // Sending the reset password URL as a response (http://localhost:3500/:token) res.status(200).send({ - resetPasswordURL: `${config.LOCAL_DEV_ENV}admin/resetpassword/${token}`, + success: 'Reset mail sent', + resetPasswordURL: `${config.FRONTEND_URL}/forgot-password/${token}`, }); return next(); }; diff --git a/backend/app/routes/admin/getAdmins.js b/backend/app/routes/admin/getAdmins.js index 8aebb616..004b03d6 100644 --- a/backend/app/routes/admin/getAdmins.js +++ b/backend/app/routes/admin/getAdmins.js @@ -15,7 +15,7 @@ const getAdminsAggregate = (match, page) => { email: 1, contact: 1, isSuperAdmin: 1, - image:1 + image: 1, }, }, { $skip: constants.PAGINATION_LIMIT.GET_ADMINS * (Number(page) - 1) }, diff --git a/backend/app/routes/admin/index.js b/backend/app/routes/admin/index.js index c8d6929f..0d4fda6e 100644 --- a/backend/app/routes/admin/index.js +++ b/backend/app/routes/admin/index.js @@ -25,8 +25,6 @@ const resetPassword = require('./resetPassword'); const updateAdmin = require('./updateAdmin'); const deleteAdmin = require('./deleteAdmin'); - - const store = multer.diskStorage({ destination: 'uploads/Admin/', filename: (req, file, cb) => { @@ -46,8 +44,8 @@ router.post('/forgotpassword', validationMiddleware(forgotPasswordSchema), forgo router.post('/resetpassword/:token', validationMiddleware(resetPasswordSchema), resetPassword); router.put('/password', validationMiddleware(passwordChangeSchema), authMiddleware, changePassword); -router.put('/:id/:token', validationMiddleware(updateAdminSchema),upload.single('image') ,updateAdmin); +router.put('/:id/:token', validationMiddleware(updateAdminSchema), upload.single('image'), updateAdmin); router.delete('/deleteAdmin', validationMiddleware(deleteAdminSchema), authMiddleware, deleteAdmin); -module.exports = router; \ No newline at end of file +module.exports = router; diff --git a/backend/app/routes/admin/resetPassword.js b/backend/app/routes/admin/resetPassword.js index 2ff7673c..d7ff6bae 100644 --- a/backend/app/routes/admin/resetPassword.js +++ b/backend/app/routes/admin/resetPassword.js @@ -29,7 +29,6 @@ module.exports = async (req, res, next) => { // Hashing the new password const hashedPassword = await argon2.hash(newPassword); - // Finding and updating the admin password const [err] = await to(Admin.findOneAndUpdate({ email }, { passwordHash: hashedPassword }, { new: true })); @@ -37,7 +36,7 @@ module.exports = async (req, res, next) => { if (err) { const error = new ErrorHandler(constants.ERRORS.INPUT, { statusCode: 400, - message: 'Something went wrong', + message: 'Reset Password Failed', user: email, errStack: 'Reset Password', }); diff --git a/backend/app/routes/admin/updateAdmin.js b/backend/app/routes/admin/updateAdmin.js index 453f7f4e..8999c222 100644 --- a/backend/app/routes/admin/updateAdmin.js +++ b/backend/app/routes/admin/updateAdmin.js @@ -1,42 +1,36 @@ -const Admin = require('../../models/Admin'); const fs = require('fs'); const path = require('path'); +const Admin = require('../../models/Admin'); -module.exports =async (req, res) => { - const admin = await Admin.findById(req.params.id); +module.exports = async (req, res) => { + const admin = await Admin.findById(req.params.id); - if (!admin) { - return res.status(404).json({ error: 'Admin not found' }); - } + if (!admin) { + return res.status(404).json({ error: 'Admin not found' }); + } - // Delete previous image if it exists - if (admin.image && admin.image!=="undefined" && req.file?.path) { - if (fs.existsSync(path.join(__dirname,'..' ,'..','..', admin.image))) { - fs.unlinkSync(path.join(__dirname,'..' ,'..','..', admin.image)); - } + // Delete previous image if it exists + if (admin.image && admin.image !== 'undefined' && req.file?.path) { + if (fs.existsSync(path.join(__dirname, '..', '..', '..', admin.image))) { + fs.unlinkSync(path.join(__dirname, '..', '..', '..', admin.image)); } - - try { - const updateFields = { - firstName:req.body.firstName, - lastName:req.body.lastName, - contact:req.body.contact, - username:req.body.username - }; + } + + try { + const updateFields = { + firstName: req.body.firstName, + lastName: req.body.lastName, + contact: req.body.contact, + username: req.body.username, + }; if (req.file?.path) { updateFields.image = req.file.path; - }else{ + } else { updateFields.image = admin.image; } - const updatedAdmin = await Admin.findByIdAndUpdate( - req.params.id, - { $set: updateFields }, - { new: true } - ); - return res.status(200).json({"Req.Body":updateFields,"updatedDoc":updatedAdmin}); - } catch (err) { - return res.status(500).json(err); - } - - res.send('Done'); + const updatedAdmin = await Admin.findByIdAndUpdate(req.params.id, { $set: updateFields }, { new: true }); + return res.status(200).json({ 'Req.Body': updateFields, updatedDoc: updatedAdmin }); + } catch (err) { + return res.status(500).json(err); + } }; diff --git a/backend/app/routes/broadcast/@validationSchema/index.js b/backend/app/routes/broadcast/@validationSchema/index.js index 934ef07f..d460c4d5 100644 --- a/backend/app/routes/broadcast/@validationSchema/index.js +++ b/backend/app/routes/broadcast/@validationSchema/index.js @@ -15,12 +15,11 @@ const updateBroadcastValidationSchema = Joi.object().keys({ title: Joi.string(), content: Joi.string(), link: Joi.string().uri(), - expiresOn: Joi.date() - .min(new Date(new Date() - 100000)), + expiresOn: Joi.date().min(new Date(new Date() - 100000)), imageUrl: Joi.array().min(1).items(Joi.string().uri()), tags: Joi.array().min(1).items(Joi.string()), isApproved: Joi.boolean().required(), - id : Joi.string().min(24).max(24).required() + id: Joi.string().min(24).max(24).required(), }); const getBroadcastsValidationSchema = Joi.object().keys({ @@ -33,5 +32,5 @@ const getBroadcastsValidationSchema = Joi.object().keys({ module.exports = { postBroadcastValidationSchema, getBroadcastsValidationSchema, - updateBroadcastValidationSchema + updateBroadcastValidationSchema, }; diff --git a/backend/app/routes/broadcast/index.js b/backend/app/routes/broadcast/index.js index 0b538a1f..9ca4be16 100644 --- a/backend/app/routes/broadcast/index.js +++ b/backend/app/routes/broadcast/index.js @@ -2,7 +2,11 @@ const router = require('express').Router({ mergeParams: true }); const validationMiddleware = require('../../../helpers/middlewares/validation'); const { authMiddleware } = require('../../../helpers/middlewares/auth'); -const { postBroadcastValidationSchema, getBroadcastsValidationSchema, updateBroadcastValidationSchema } = require('./@validationSchema'); +const { + postBroadcastValidationSchema, + getBroadcastsValidationSchema, + updateBroadcastValidationSchema, +} = require('./@validationSchema'); const postBroadcast = require('./postBroadcast'); const deleteBroadcast = require('./deleteBroadcast'); const getBroadcasts = require('./getBroadcasts'); diff --git a/backend/app/routes/broadcast/updateBroadcast.js b/backend/app/routes/broadcast/updateBroadcast.js index be508474..9d2cecf8 100644 --- a/backend/app/routes/broadcast/updateBroadcast.js +++ b/backend/app/routes/broadcast/updateBroadcast.js @@ -3,46 +3,46 @@ const Broadcast = require('../../models/Broadcast'); const { ErrorHandler } = require('../../../helpers/error'); const constants = require('../../../constants'); -module.exports = async (req, res, next) => { - if(Object.keys(req.body).length <= 1) { - return res.status(200).send({ - message : "Not Sufficient Data" - }) - } - - const data = { - ...req.body - }; - - delete data.id; - - const [err, result] = await to(Broadcast.findOneAndUpdate({ _id : req.body.id }, { $set : data })); - - // error occured due to the some problem - if(err) { - const error = new ErrorHandler(constants.ERRORS.DATABASE, { - statusCode: 500, - message: 'Database Error', - errStack: err, - }); - - return next(error); - } - - // if result is null that means broadcast with given id is not exist in collection - if(result === null) { - const broadcastNotExistsError = new ErrorHandler(constants.ERRORS.INPUT, { - statusCode: 400, - message: 'Broadcast Not Exist...', - }); - - return next(broadcastNotExistsError); - } - - // success response - res.status(200).send({ - message : "Broadcast Updated..." - }); - - return next(); -} \ No newline at end of file +module.exports = async (req, res, next) => { + if (Object.keys(req.body).length <= 1) { + return res.status(200).send({ + message: 'Not Sufficient Data', + }); + } + + const data = { + ...req.body, + }; + + delete data.id; + + const [err, result] = await to(Broadcast.findOneAndUpdate({ _id: req.body.id }, { $set: data })); + + // error occured due to the some problem + if (err) { + const error = new ErrorHandler(constants.ERRORS.DATABASE, { + statusCode: 500, + message: 'Database Error', + errStack: err, + }); + + return next(error); + } + + // if result is null that means broadcast with given id is not exist in collection + if (result === null) { + const broadcastNotExistsError = new ErrorHandler(constants.ERRORS.INPUT, { + statusCode: 400, + message: 'Broadcast Not Exist...', + }); + + return next(broadcastNotExistsError); + } + + // success response + res.status(200).send({ + message: 'Broadcast Updated...', + }); + + return next(); +}; diff --git a/backend/app/routes/contactUs/delete.js b/backend/app/routes/contactUs/delete.js index be59b6ff..b4529a1e 100644 --- a/backend/app/routes/contactUs/delete.js +++ b/backend/app/routes/contactUs/delete.js @@ -1,7 +1,7 @@ const mongoose = require('mongoose'); const ContactUs = require('../../models/contactUs'); -module.exports = async (req, res, next) => { +module.exports = async (req, res) => { try { const payload = res.locals.decode; const { contactUsId } = req.body; @@ -23,4 +23,4 @@ module.exports = async (req, res, next) => { } catch (error) { return res.status(500).json({ error: 'Internal server error' }); } -} \ No newline at end of file +}; diff --git a/backend/app/routes/faq/index.js b/backend/app/routes/faq/index.js index bfa41276..c3877111 100644 --- a/backend/app/routes/faq/index.js +++ b/backend/app/routes/faq/index.js @@ -5,10 +5,11 @@ const FAQValidationSchema = require('./@validationSchema'); const validation = require('../../../helpers/middlewares/validation'); const deleteFaq = require('./deleteFaq'); const updateFaq = require('./updateFaq'); -const {authMiddleware}=require('../../../helpers/middlewares/auth') +const { authMiddleware } = require('../../../helpers/middlewares/auth'); + router.post('/postFaq', validation(FAQValidationSchema), faq); router.get('/getFaq', getfaq); -router.put('/deleteFaq',authMiddleware, deleteFaq); -router.patch('/updateFaq',updateFaq); +router.put('/deleteFaq', authMiddleware, deleteFaq); +router.patch('/updateFaq', updateFaq); module.exports = router; diff --git a/backend/app/routes/faq/post.js b/backend/app/routes/faq/post.js index 805aa958..7068423f 100644 --- a/backend/app/routes/faq/post.js +++ b/backend/app/routes/faq/post.js @@ -4,7 +4,7 @@ const { ErrorHandler } = require('../../../helpers/error'); const constants = require('../../../constants'); module.exports = async (req, res, next) => { - const [err,response] = await to(FAQ.create({ ...req.body })); + const [err, response] = await to(FAQ.create({ ...req.body })); if (err) { const error = new ErrorHandler(constants.ERRORS.DATABASE, { statusCode: 500, @@ -14,7 +14,8 @@ module.exports = async (req, res, next) => { return next(error); } res.status(200).send({ - message: 'FAQ has been added',response:response + message: 'FAQ has been added', + response, }); return next(); }; diff --git a/backend/app/routes/faq/updateFaq.js b/backend/app/routes/faq/updateFaq.js index bd94e395..0e89ff5c 100644 --- a/backend/app/routes/faq/updateFaq.js +++ b/backend/app/routes/faq/updateFaq.js @@ -1,20 +1,25 @@ -const FAQ = require('../../models/faq'); +const FAQS = require('../../models/faq'); -module.exports = async(req,res,next) => { - try { - let faqId = req.body.faqId; - let faq = await FAQ.findById(faqId); - if(faq == null) { - return res.json({message:"invalid id"}); - } - - const updatedFaq = {question:req.body.question,answer:req.body.answer,isActive:req.body.isActive,tags:req.body.tags}; - FAQ.findByIdAndUpdate(faqId,{$set:updatedFaq},{new:true},function(err,faq) { - if (err) return res.status(500).send({error: err}); - return res.status(200).send({message:"FAQ updated successfully",response:faq}); - }); +module.exports = async (req, res) => { + try { + const { faqId } = req.body; + const faq = await FAQS.findById(faqId); + if (faq == null) { + return res.json({ message: 'invalid id' }); } - catch(err) { - return res.status(500).json({error:"some went wrong"}); - } -} + + const updatedFaq = { + question: req.body.question, + answer: req.body.answer, + isActive: req.body.isActive, + tags: req.body.tags, + }; + FAQS.findByIdAndUpdate(faqId, { $set: updatedFaq }, { new: true }, (err, faqq) => { + if (err) return res.status(500).send({ error: err }); + return res.status(200).send({ message: 'FAQ updated successfully', response: faqq }); + }); + } catch (err) { + return res.status(500).json({ error: 'some went wrong' }); + } + return null; +}; diff --git a/backend/app/routes/index.js b/backend/app/routes/index.js index 0919698f..925657db 100644 --- a/backend/app/routes/index.js +++ b/backend/app/routes/index.js @@ -6,7 +6,7 @@ const tinyURL = require('./tinyURL'); const broadcast = require('./broadcast'); const faq = require('./faq'); const joinUs = require('./joinUs'); -const contactus = require('./contactUs') +const contactus = require('./contactUs'); const question = require('./Q&A/question'); const answer = require('./Q&A/answers'); const teamMember = require('./teamMember'); diff --git a/backend/app/routes/joinUs/deleteJoinUs.js b/backend/app/routes/joinUs/deleteJoinUs.js index 5d5a2aef..fae856e8 100644 --- a/backend/app/routes/joinUs/deleteJoinUs.js +++ b/backend/app/routes/joinUs/deleteJoinUs.js @@ -1,16 +1,14 @@ const joinUsModel = require('../../models/joinUs'); -module.exports = async(req,res,next) => { - try { - const id = req.body.itemId - const result = await joinUsModel.findByIdAndDelete(id); - if(!result) { - return res.json({error:"Invalid id"}); - } - return res.json({message : "Deleted successfully"}) - +module.exports = async (req, res) => { + try { + const id = req.body.itemId; + const result = await joinUsModel.findByIdAndDelete(id); + if (!result) { + return res.json({ error: 'Invalid id' }); } - catch(err) { - return res.json({error: "Some internal server error"}); - } -} + return res.json({ message: 'Deleted successfully' }); + } catch (err) { + return res.json({ error: 'Some internal server error' }); + } +}; diff --git a/backend/app/routes/joinUs/index.js b/backend/app/routes/joinUs/index.js index 8e20ee46..8bd7c43d 100644 --- a/backend/app/routes/joinUs/index.js +++ b/backend/app/routes/joinUs/index.js @@ -3,11 +3,11 @@ const postJoinUs = require('./post'); const getJoinUs = require('./get'); const JoinUsValidationSchema = require('./@validationSchema'); const validation = require('../../../helpers/middlewares/validation'); -const {authMiddleware} = require('../../../helpers/middlewares/auth') -const deleteJoinUs = require("./deleteJoinUs") +const { authMiddleware } = require('../../../helpers/middlewares/auth'); +const deleteJoinUs = require('./deleteJoinUs'); router.post('/', validation(JoinUsValidationSchema), postJoinUs); router.get('/', authMiddleware, getJoinUs); -router.delete('/deleteJoinUs',deleteJoinUs) +router.delete('/deleteJoinUs', deleteJoinUs); module.exports = router; diff --git a/backend/app/routes/joinUs/post.js b/backend/app/routes/joinUs/post.js index 47c198e5..b4a359b3 100644 --- a/backend/app/routes/joinUs/post.js +++ b/backend/app/routes/joinUs/post.js @@ -7,7 +7,7 @@ const sendEmail = require('../../../utility/sendEmail'); const { JoinUsMailTemplate } = require('../../../utility/emailTemplates'); module.exports = async (req, res, next) => { - const [err,createdResponse] = await to(JoinUs.create({ ...req.body })); + const [err, createdResponse] = await to(JoinUs.create({ ...req.body })); if (err) { const error = new ErrorHandler(constants.ERRORS.DATABASE, { statusCode: 500, @@ -46,7 +46,7 @@ module.exports = async (req, res, next) => { res.status(200).send({ message: 'Request Submitted Successfully', - response : createdResponse + response: createdResponse, }); return next(); }; diff --git a/backend/app/routes/resources/@validationSchema/index.js b/backend/app/routes/resources/@validationSchema/index.js index b0c94284..08a17daa 100644 --- a/backend/app/routes/resources/@validationSchema/index.js +++ b/backend/app/routes/resources/@validationSchema/index.js @@ -11,4 +11,4 @@ const postResourceValidationSchema = Joi.object().keys({ tags: Joi.array().min(1).items(Joi.string()).required(), }); -module.exports = postResourceValidationSchema; \ No newline at end of file +module.exports = postResourceValidationSchema; diff --git a/backend/app/routes/resources/postResource.js b/backend/app/routes/resources/postResource.js index 9ff6c3c4..7857cc49 100644 --- a/backend/app/routes/resources/postResource.js +++ b/backend/app/routes/resources/postResource.js @@ -15,7 +15,7 @@ module.exports = async (req, res, next) => { } res.status(200).send({ message: 'Resource added successfully', - response: response, + response, }); return next(); }; diff --git a/backend/app/routes/teamMember/deleteTeamMember.js b/backend/app/routes/teamMember/deleteTeamMember.js index 85c54b53..76e6235a 100644 --- a/backend/app/routes/teamMember/deleteTeamMember.js +++ b/backend/app/routes/teamMember/deleteTeamMember.js @@ -1,11 +1,11 @@ -const teamMemberModel = require('../../models/TeamMember'); const fs = require('fs'); const path = require('path'); +const teamMemberModel = require('../../models/TeamMember'); -module.exports = async (req, res, next) => { +module.exports = async (req, res) => { try { const payload = res.locals.decode; - const memberId = req.body.memberId; + const { memberId } = req.body; if (payload.isSuperAdmin === false) { return res.status(401).json({ error: 'You are not an admin' }); } diff --git a/backend/app/routes/teamMember/getTeamMemberById.js b/backend/app/routes/teamMember/getTeamMemberById.js index ed0012f7..d8153621 100644 --- a/backend/app/routes/teamMember/getTeamMemberById.js +++ b/backend/app/routes/teamMember/getTeamMemberById.js @@ -3,7 +3,6 @@ const TeamMemberModel = require('../../models/TeamMember'); const { ErrorHandler } = require('../../../helpers/error'); const constants = require('../../../constants'); - module.exports = async (req, res, next) => { const memberId = req.params.id; const [err, member] = await to(TeamMemberModel.findById(memberId)); @@ -13,7 +12,7 @@ module.exports = async (req, res, next) => { statusCode: 500, message: 'Mongo Error: Fetching failed', errStack: err, - } + }; const error = new ErrorHandler(constants.ERRORS.DATABASE, errOptions); return next(error); } @@ -23,10 +22,10 @@ module.exports = async (req, res, next) => { statusCode: 404, message: `Resource Not Found: No team member with id ${memberId}`, errStack: err, - } + }; const error = new ErrorHandler(constants.ERRORS.DATABASE, errOptions); return next(error); } return res.json(member); -} +}; diff --git a/backend/app/routes/teamMember/getTeamMembers.js b/backend/app/routes/teamMember/getTeamMembers.js index 9f1b3fc3..d8340dfe 100644 --- a/backend/app/routes/teamMember/getTeamMembers.js +++ b/backend/app/routes/teamMember/getTeamMembers.js @@ -3,7 +3,6 @@ const TeamMemberModel = require('../../models/TeamMember'); const { ErrorHandler } = require('../../../helpers/error'); const constants = require('../../../constants'); - module.exports = async (req, res, next) => { const [err, members] = await to(TeamMemberModel.find()); @@ -12,10 +11,10 @@ module.exports = async (req, res, next) => { statusCode: 500, message: 'Mongo Error: Fetching failed', errStack: err, - } + }; const error = new ErrorHandler(constants.ERRORS.DATABASE, errOptions); return next(error); } return res.json(members); -} +}; diff --git a/backend/app/routes/teamMember/index.js b/backend/app/routes/teamMember/index.js index 0a0ba9a5..f59a9ad3 100644 --- a/backend/app/routes/teamMember/index.js +++ b/backend/app/routes/teamMember/index.js @@ -21,6 +21,6 @@ const upload = multer({ storage: store }); router.get('/getTeamMembers/', getTeamMembers); router.get('/getTeamMember/:id', getTeamMemberById); router.post('/addTeamMember', authMiddleware, upload.single('image'), addTeam); -router.put('/updateTeamMember',authMiddleware,upload.single('image'),updateTeamMember); -router.delete("/deleteTeamMember",authMiddleware,deleteTeamMember); +router.put('/updateTeamMember', authMiddleware, upload.single('image'), updateTeamMember); +router.delete('/deleteTeamMember', authMiddleware, deleteTeamMember); module.exports = router; diff --git a/backend/app/routes/teamMember/updateTeamMember.js b/backend/app/routes/teamMember/updateTeamMember.js index c9492699..39e540d4 100644 --- a/backend/app/routes/teamMember/updateTeamMember.js +++ b/backend/app/routes/teamMember/updateTeamMember.js @@ -1,30 +1,29 @@ const TeamMemberModel = require('../../models/TeamMember'); -module.exports = async(req,res) => { - try { - const payload = res.locals.decode; - let teamMember = await TeamMemberModel.findById(req.body.teamMemberId) - if (payload.isSuperAdmin === false) { - return res.status(401).json({ error: 'You are not an admin' }); - } - if(teamMember == null) { - return res.status(401).json({ error: 'team member not found' }); - } - - const updateData = { - full_name: req.body.full_name, - image: req.file.path, - description: req.body.description, - linkedin_url: req.body.linkedin_url, - github_url: req.body.github_url, - twitter_url: req.body.twitter_url, - teams:req.body.teams, - } - const result = await TeamMemberModel.findByIdAndUpdate(req.body.teamMemberId,{$set:updateData},{new:true}); - - return res.json({message:"updated successfully",response:result}); +module.exports = async (req, res) => { + try { + const payload = res.locals.decode; + const teamMember = await TeamMemberModel.findById(req.body.teamMemberId); + if (payload.isSuperAdmin === false) { + return res.status(401).json({ error: 'You are not an admin' }); } - catch(err) { - return res.status(500).json({error:"Some went wrong"}); + if (teamMember == null) { + return res.status(401).json({ error: 'team member not found' }); } -} \ No newline at end of file + + const updateData = { + full_name: req.body.full_name, + image: req.file.path, + description: req.body.description, + linkedin_url: req.body.linkedin_url, + github_url: req.body.github_url, + twitter_url: req.body.twitter_url, + teams: req.body.teams, + }; + const result = await TeamMemberModel.findByIdAndUpdate(req.body.teamMemberId, { $set: updateData }, { new: true }); + + return res.json({ message: 'updated successfully', response: result }); + } catch (err) { + return res.status(500).json({ error: 'Some went wrong' }); + } +}; diff --git a/backend/app/routes/testimonial/index.js b/backend/app/routes/testimonial/index.js index b22e0329..659fa168 100644 --- a/backend/app/routes/testimonial/index.js +++ b/backend/app/routes/testimonial/index.js @@ -2,10 +2,8 @@ const router = require('express').Router({ mergeParams: true }); const multer = require('multer'); const { nanoid } = require('nanoid'); const path = require('path'); -const validationMiddleware = require('../../../helpers/middlewares/validation'); const { authMiddleware } = require('../../../helpers/middlewares/auth'); -const { postTestimonialValidationSchema } = require('./@validationSchema'); const postTestimonial = require('./postTestimonial'); const getTestimonials = require('./getTestimonials'); const deleteTestimonial = require('./deleteTestimonial'); diff --git a/backend/config/index.js b/backend/config/index.js index 7599e845..2f7ddf7b 100644 --- a/backend/config/index.js +++ b/backend/config/index.js @@ -11,6 +11,7 @@ const config = { CLUSTER: process.env.CLUSTER, JWT_RESET_PASSWORD_EXPIRES_IN: process.env.JWT_RESET_PASSWORD_EXPIRES_IN, LOCAL_DEV_ENV: process.env.LOCAL_DEV_ENV, + FRONTEND_URL: process.env.FRONTEND_URL, }; module.exports = config; diff --git a/backend/helpers/middlewares/cookie.js b/backend/helpers/middlewares/cookie.js index bf7bd680..86fa78b9 100644 --- a/backend/helpers/middlewares/cookie.js +++ b/backend/helpers/middlewares/cookie.js @@ -11,6 +11,7 @@ const checkVoteCookie = (req, res, next) => { } next(); + return null; }; -module.exports = { checkVoteCookie, getVoteCookieName } \ No newline at end of file +module.exports = { checkVoteCookie, getVoteCookieName }; diff --git a/backend/index.js b/backend/index.js index e5de29c6..7abc29f4 100644 --- a/backend/index.js +++ b/backend/index.js @@ -8,10 +8,7 @@ const cluster = require('./helpers/cluster'); const joinUs = require('./app/models/joinUs'); const contactUs = require('./app/models/contactUs'); const sendEmail = require('./utility/sendEmail'); -const { - JoinUsCronJobMailTemplate, - ContactUsCronJobMailTemplate, -} = require('./utility/emailTemplates'); +const { JoinUsCronJobMailTemplate, ContactUsCronJobMailTemplate } = require('./utility/emailTemplates'); const Admin = require('./app/models/Admin'); cronJob('0 0 2 * *', async (req, res, next) => { diff --git a/backend/package.json b/backend/package.json index b9cb2775..54b8090e 100644 --- a/backend/package.json +++ b/backend/package.json @@ -73,7 +73,7 @@ "husky": "^4.3.8", "lint-staged": "^10.5.3", "mocha": "^8.3.2", - "nodemon": "^2.0.6", + "nodemon": "^2.0.22", "prettier": "2.2.1" } } diff --git a/backend/tests/routes/FAQ/updateFaq.test.js b/backend/tests/routes/FAQ/updateFaq.test.js index a48593b5..d2a148e7 100644 --- a/backend/tests/routes/FAQ/updateFaq.test.js +++ b/backend/tests/routes/FAQ/updateFaq.test.js @@ -56,30 +56,29 @@ describe('Test to update FAQ:', () => { expect(res.status).equal(200); expect(res.body.message).to.equal('FAQ has been added'); id = res.body.response._id; - done() + done(); }) .catch(done); }); - //step 4 : update faq in db - it('update faq', (done)=> { + // step 4 : update faq in db + it('update faq', (done) => { const UpdatedFAQData = { faqId: id, question: 'This is Test Question', answer: 'updating answer', isActive: true, - tags: ['tag1', 'tag2', 'tag3','tag5'], + tags: ['tag1', 'tag2', 'tag3', 'tag5'], }; chai .request(server) - .patch("/updateFaq") - .set("content-type","application/json") + .patch('/updateFaq') + .set('content-type', 'application/json') .send(UpdatedFAQData) - .end((err,res) => { - expect(res.body.message).to.equal("FAQ updated successfully") + .end((err, res) => { + expect(res.body.message).to.equal('FAQ updated successfully'); done(); - }) - + }); }); }); diff --git a/backend/tests/routes/Q&A/updateAnswerStatus.test.js b/backend/tests/routes/Q&A/updateAnswerStatus.test.js index b017d5d5..746ef792 100644 --- a/backend/tests/routes/Q&A/updateAnswerStatus.test.js +++ b/backend/tests/routes/Q&A/updateAnswerStatus.test.js @@ -8,51 +8,51 @@ chai.use(chaiHttp); // Test for updating answer status describe('Test for updating answer status:', () => { + let id = ''; - let id = ''; + // Step 1 : Post The Answer + it('post answer at /answers', (done) => { + const questionData = { + title: 'testtitle', + description: + '--this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description --', - // Step 1 : Post The Answer - it('post answer at /answers', (done) => { - const questionData = { - title: 'testtitle', - description: - '--this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description --', - - tags: ['tag1', 'tag2', 'tag3'], - }; - // Saving a question in database for which answer will be posted - const postedQuestion = new Question(questionData); - postedQuestion.save(); - - const answerData = { - question_id: postedQuestion._id, - created_by: 'test user', - answer: 'this is test answer', - created_on: new Date(Date.now()), - }; - - // request to post answer - chai - .request(server) - .post('/answers') - .send(answerData) - .then((res) => { - expect(res.body.message).to.equal('Answer has been added'); - id=res.body.id; - done(); - }) - .catch(done); - }); + tags: ['tag1', 'tag2', 'tag3'], + }; + // Saving a question in database for which answer will be posted + const postedQuestion = new Question(questionData); + postedQuestion.save(); - // Step 2 : Updating Answer Status - it('Updating answer at /answers/updateStatus', (done) => { - chai - .request(server) - .patch('/answers/updateStatus') - .send({ id: id, status : true }) - .then((res) => { - expect(res.body.message).to.equal('Status Updated...'); - done(); - }).catch(done); - }); + const answerData = { + question_id: postedQuestion._id, + created_by: 'test user', + answer: 'this is test answer', + created_on: new Date(Date.now()), + }; + + // request to post answer + chai + .request(server) + .post('/answers') + .send(answerData) + .then((res) => { + expect(res.body.message).to.equal('Answer has been added'); + id = res.body.id; + done(); + }) + .catch(done); + }); + + // Step 2 : Updating Answer Status + it('Updating answer at /answers/updateStatus', (done) => { + chai + .request(server) + .patch('/answers/updateStatus') + .send({ id, status: true }) + .then((res) => { + expect(res.body.message).to.equal('Status Updated...'); + done(); + }) + .catch(done); + }); }); diff --git a/backend/tests/routes/Q&A/updateQuestionStatus.test.js b/backend/tests/routes/Q&A/updateQuestionStatus.test.js index e4a00140..168920f5 100644 --- a/backend/tests/routes/Q&A/updateQuestionStatus.test.js +++ b/backend/tests/routes/Q&A/updateQuestionStatus.test.js @@ -7,40 +7,40 @@ chai.use(chaiHttp); // Test for updating question status describe('Test for updating question status:', () => { + let id = ''; - let id = ""; + // Step 1 : Posting Question + it('post question at /question', (done) => { + const questionData = { + title: 'testtitle', + description: + '--this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description --', - // Step 1 : Posting Question - it('post question at /question', (done) => { - const questionData = { - title: 'testtitle', - description: - '--this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description ----this is test description --', - - tags: ['tag1', 'tag2', 'tag3'], - }; + tags: ['tag1', 'tag2', 'tag3'], + }; - chai - .request(server) - .post('/question') - .send(questionData) - .then((res) => { - expect(res.body.message).to.equal('Question has been added'); - id = res.body.id; - done(); - }) - .catch(done); - }); + chai + .request(server) + .post('/question') + .send(questionData) + .then((res) => { + expect(res.body.message).to.equal('Question has been added'); + id = res.body.id; + done(); + }) + .catch(done); + }); - // Updating Status - it('Updating question at /question/updateStatus', (done) => { - chai - .request(server) - .patch('/question/updateStatus') - .send({ id: id, status : true }) - .then((res) => { - expect(res.body.message).to.equal('Status Updated...'); - done(); - }).catch(done); - }); + // Updating Status + it('Updating question at /question/updateStatus', (done) => { + chai + .request(server) + .patch('/question/updateStatus') + .send({ id, status: true }) + .then((res) => { + expect(res.body.message).to.equal('Status Updated...'); + done(); + }) + .catch(done); + }); }); diff --git a/backend/tests/routes/admin/deleteAdmin.test.js b/backend/tests/routes/admin/deleteAdmin.test.js index b8885715..d3560b06 100644 --- a/backend/tests/routes/admin/deleteAdmin.test.js +++ b/backend/tests/routes/admin/deleteAdmin.test.js @@ -6,87 +6,89 @@ const server = require('../../../index'); chai.use(chaiHttp); // Test for delete Admin -describe("Test For Delete Admin : ", () => { - let token = ''; - let id = ''; +describe('Test For Delete Admin : ', () => { + let token = ''; + let id = ''; - //Step 1 - login as super admin - it('log in as admin at /auth/login', (done) => { - const loginData = { - email: 'kajolkumarisingh222@gmail.com', - password: 'password', - }; - - chai - .request(server) - .post('/auth/login') - .send(loginData) - .then((res) => { - expect(res.status).to.equal(200); - expect(res.body.email).to.equal(loginData.email); - expect(res.body.isSuperAdmin).to.equal(true); - expect(res.body.token).to.be.a('string'); - token = res.body.token; - done(); - }) - .catch(done); - }); + // Step 1 - login as super admin + it('log in as admin at /auth/login', (done) => { + const loginData = { + email: 'kajolkumarisingh222@gmail.com', + password: 'password', + }; - // Step 2 - Post The New Admin - it('Post admin at /admin', (done) => { - const adminData = { - email: 'demo-user@gmail.com', - password: 'demo@123-USER', - firstName : 'Demo', - lastName : 'User' - }; - - chai - .request(server) - .post('/admin') - .set('Authorization', `Bearer ${token}`) - .send(adminData) - .then((res) => { - expect(res.status).to.equal(200); - id = res.body._id; - done(); - }) - .catch(done); - }); + chai + .request(server) + .post('/auth/login') + .send(loginData) + .then((res) => { + expect(res.status).to.equal(200); + expect(res.body.email).to.equal(loginData.email); + expect(res.body.isSuperAdmin).to.equal(true); + expect(res.body.token).to.be.a('string'); + token = res.body.token; + done(); + }) + .catch(done); + }); - //Step 3 - Delete The Admin - it("Delete Admin At /admin/deleteAdmin", (done) => { - const data = { - id : id - }; + // Step 2 - Post The New Admin + it('Post admin at /admin', (done) => { + const adminData = { + email: 'demo-user@gmail.com', + password: 'demo@123-USER', + firstName: 'Demo', + lastName: 'User', + }; - chai - .request(server) - .delete('/admin/deleteAdmin') - .set('Authorization', `Bearer ${token}`) - .send(data) - .then((res) => { - expect(res.status).to.equal(200); - expect(res.body.message).to.be.equal("Admin deleted successfully") - done(); - }).catch(done); - }); - - //Step 4 - Delete Not Exist Admin - it("Delete Admin At /admin/deleteAdmin", (done) => { - const data = { - id : id - }; + chai + .request(server) + .post('/admin') + .set('Authorization', `Bearer ${token}`) + .send(adminData) + .then((res) => { + expect(res.status).to.equal(200); + id = res.body._id; + done(); + }) + .catch(done); + }); - chai - .request(server) - .delete('/admin/deleteAdmin') - .set('Authorization', `Bearer ${token}`) - .send(data) - .then((res) => { - expect(res.status).to.equal(400); - expect(res.body.message).to.be.equal("Admin doesn't exist") - done(); - }).catch(done); - }); -}) \ No newline at end of file + // Step 3 - Delete The Admin + it('Delete Admin At /admin/deleteAdmin', (done) => { + const data = { + id, + }; + + chai + .request(server) + .delete('/admin/deleteAdmin') + .set('Authorization', `Bearer ${token}`) + .send(data) + .then((res) => { + expect(res.status).to.equal(200); + expect(res.body.message).to.be.equal('Admin deleted successfully'); + done(); + }) + .catch(done); + }); + + // Step 4 - Delete Not Exist Admin + it('Delete Admin At /admin/deleteAdmin', (done) => { + const data = { + id, + }; + + chai + .request(server) + .delete('/admin/deleteAdmin') + .set('Authorization', `Bearer ${token}`) + .send(data) + .then((res) => { + expect(res.status).to.equal(400); + expect(res.body.message).to.be.equal("Admin doesn't exist"); + done(); + }) + .catch(done); + }); +}); diff --git a/backend/tests/routes/broadcast/updateBroadcast.test.js b/backend/tests/routes/broadcast/updateBroadcast.test.js index e6245b2f..e8cf2470 100644 --- a/backend/tests/routes/broadcast/updateBroadcast.test.js +++ b/backend/tests/routes/broadcast/updateBroadcast.test.js @@ -5,79 +5,79 @@ const server = require('../../../index'); chai.use(chaiHttp); -describe("Test For Update Broadcast : " , () => { - let token = ''; - let id = ''; - - // Step 1 - login as admin - it('log in as admin at /auth/login', (done) => { - const loginData = { - email: 'kajolkumarisingh222@gmail.com', - password: 'password', - }; - - chai - .request(server) - .post('/auth/login') - .send(loginData) - .then((res) => { - expect(res.status).to.equal(200); - expect(res.body.email).to.equal(loginData.email); - expect(res.body.isSuperAdmin).to.equal(true); - expect(res.body.token).to.be.a('string'); - token = res.body.token; - done(); - }) - .catch(done); - }); - - // Step 2 - add broadcast to DB - it('add broadcast to DB at /broadcast', (done) => { - const broadcastData = { - title: 'testtitle', - content: - '--this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content --', - link: 'https://abc.xyz', - expiresOn: new Date(), - imageUrl: ['http://imageurl@imageurl.com', 'http://imageurl@imageurl.com', 'http://imageurl@imageurl.com'], - tags: ['tag1', 'tag2', 'tag3'], - }; - - chai - .request(server) - .post('/broadcast') - .set('Authorization', `Bearer ${token}`) - .send(broadcastData) - .then((res) => { - expect(res.status).to.equal(200); - expect(res.body.message).to.equal('Broadcast added successfully'); - id = res.body.id; - done(); - }) - .catch(done); - }); +describe('Test For Update Broadcast : ', () => { + let token = ''; + let id = ''; - // Step 3 - update broadcast + // Step 1 - login as admin + it('log in as admin at /auth/login', (done) => { + const loginData = { + email: 'kajolkumarisingh222@gmail.com', + password: 'password', + }; - it('update broadcast at /broadcast/update', (done) => { - const newData = { - title : "test title updated", - link : "https://xyz.abc", - expiresOn: new Date(), - tags: ['tag1', 'tag2', 'tag4'], - id : id - } + chai + .request(server) + .post('/auth/login') + .send(loginData) + .then((res) => { + expect(res.status).to.equal(200); + expect(res.body.email).to.equal(loginData.email); + expect(res.body.isSuperAdmin).to.equal(true); + expect(res.body.token).to.be.a('string'); + token = res.body.token; + done(); + }) + .catch(done); + }); - chai - .request(server) - .patch('/broadcast/update') - .set('Authorization', `Bearer ${token}`) - .send(newData) - .then((res) => { - expect(res.status).to.equal(200); - expect(res.body.message).to.equal('Broadcast Updated...'); - done(); - }) - .catch(done); - }) -}) \ No newline at end of file + // Step 2 - add broadcast to DB + it('add broadcast to DB at /broadcast', (done) => { + const broadcastData = { + title: 'testtitle', + content: + '--this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content ----this is test content --', + link: 'https://abc.xyz', + expiresOn: new Date(), + imageUrl: ['http://imageurl@imageurl.com', 'http://imageurl@imageurl.com', 'http://imageurl@imageurl.com'], + tags: ['tag1', 'tag2', 'tag3'], + }; + + chai + .request(server) + .post('/broadcast') + .set('Authorization', `Bearer ${token}`) + .send(broadcastData) + .then((res) => { + expect(res.status).to.equal(200); + expect(res.body.message).to.equal('Broadcast added successfully'); + id = res.body.id; + done(); + }) + .catch(done); + }); + + // Step 3 - update broadcast + + it('update broadcast at /broadcast/update', (done) => { + const newData = { + title: 'test title updated', + link: 'https://xyz.abc', + expiresOn: new Date(), + tags: ['tag1', 'tag2', 'tag4'], + id, + }; + + chai + .request(server) + .patch('/broadcast/update') + .set('Authorization', `Bearer ${token}`) + .send(newData) + .then((res) => { + expect(res.status).to.equal(200); + expect(res.body.message).to.equal('Broadcast Updated...'); + done(); + }) + .catch(done); + }); +}); diff --git a/backend/tests/routes/joinUs/deleteJoinUs.test.js b/backend/tests/routes/joinUs/deleteJoinUs.test.js index 205c7dc9..7a2ef612 100644 --- a/backend/tests/routes/joinUs/deleteJoinUs.test.js +++ b/backend/tests/routes/joinUs/deleteJoinUs.test.js @@ -1,50 +1,50 @@ -const chai = require('chai') -const {expect} = require("chai") -const chaiHttp = require('chai-http') +const chai = require('chai'); +const { expect } = require('chai'); +const chaiHttp = require('chai-http'); const server = require('../../../index'); chai.use(chaiHttp); -//Test for deleting Join us -describe('Test for delete Join us',()=> { - let id = ''; +// Test for deleting Join us +describe('Test for delete Join us', () => { + let id = ''; - //Step 1: add join us to DB - it('Add joinus to Db at /joinUs',(done)=> { - const joinUsData = { - name: 'AmanTest', - email: 'Aman@test.com', - linkdin: 'https://www.linkedin.com/in/test', - description: 'Testing deleting join us api', - year: '1th', - college: 'GSSIPU University', - contact: '0123456789', - interestedDomain: ['Backend'], - department: 'CS(AIML)', - }; + // Step 1: add join us to DB + it('Add joinus to Db at /joinUs', (done) => { + const joinUsData = { + name: 'AmanTest', + email: 'Aman@test.com', + linkdin: 'https://www.linkedin.com/in/test', + description: 'Testing deleting join us api', + year: '1th', + college: 'GSSIPU University', + contact: '0123456789', + interestedDomain: ['Backend'], + department: 'CS(AIML)', + }; - chai - .request(server) - .post('/joinUs') - .send(joinUsData) - .then((res) => { - expect(res.status).to.equal(200); - id = res.body.response._id - done(); - }) - .catch(done); - }); + chai + .request(server) + .post('/joinUs') + .send(joinUsData) + .then((res) => { + expect(res.status).to.equal(200); + id = res.body.response._id; + done(); + }) + .catch(done); + }); - //step 2 : delete joinUs from DB - it('Delete joinus at /joinUs/deleteJoinUs',(done)=> { - chai - .request(server) - .delete("/joinUs/deleteJoinUs") - .send({itemId:id}) - .then((res)=> { - expect(res.body.message).to.equal("Deleted successfully") - done(); - }) - .catch(done); - }) -}) \ No newline at end of file + // step 2 : delete joinUs from DB + it('Delete joinus at /joinUs/deleteJoinUs', (done) => { + chai + .request(server) + .delete('/joinUs/deleteJoinUs') + .send({ itemId: id }) + .then((res) => { + expect(res.body.message).to.equal('Deleted successfully'); + done(); + }) + .catch(done); + }); +}); diff --git a/backend/tests/routes/teamMember/deleteTeamMember.js b/backend/tests/routes/teamMember/deleteTeamMember.js index f03e23b3..6ac2841e 100644 --- a/backend/tests/routes/teamMember/deleteTeamMember.js +++ b/backend/tests/routes/teamMember/deleteTeamMember.js @@ -2,73 +2,74 @@ const chai = require('chai'); const { expect } = require('chai'); const chaiHttp = require('chai-http'); const server = require('../../../index'); + chai.use(chaiHttp); -describe('Delete team member from DB',()=> { - let token = '' - let id = '' - //Step 1 : login as admin - it('log in as admin at /auth/login', (done) => { - const loginData = { - email: 'kajolkumarisingh222@gmail.com', - password: 'password', - }; - - chai - .request(server) - .post('/auth/login') - .send(loginData) - .then((res) => { - expect(res.status).to.equal(200); - expect(res.body.email).to.equal(loginData.email); - expect(res.body.isSuperAdmin).to.equal(true); - expect(res.body.token).to.be.a('string'); - token = res.body.token; - done(); - }) - .catch(done); - }); +describe('Delete team member from DB', () => { + let token = ''; + let id = ''; + // Step 1 : login as admin + it('log in as admin at /auth/login', (done) => { + const loginData = { + email: 'kajolkumarisingh222@gmail.com', + password: 'password', + }; + + chai + .request(server) + .post('/auth/login') + .send(loginData) + .then((res) => { + expect(res.status).to.equal(200); + expect(res.body.email).to.equal(loginData.email); + expect(res.body.isSuperAdmin).to.equal(true); + expect(res.body.token).to.be.a('string'); + token = res.body.token; + done(); + }) + .catch(done); + }); - //step 2 add team member to DB - it('Add team member at /teamMember/addTeamMember',(done)=> { - const testData = { - full_name : "Aman test", - description :"This is for testing the api" , - linkedlin_url : "https//www.linkedin.in/AmanTest", - github_url : "https/www.github.com/Aman16-ai", - twitter_url : "https/www.tiwtter.com/Amanteset", - teams: ["Aman","anubhav"] - } - chai - .request(server) - .post('/teamMember/addTeamMember') - .set('Authorization', `Bearer ${token}`) - .set('content-type','multipart/form-data') - .field("fullName",testData.full_name) - .field("description",testData.description) - .field("linkedlinUrl",testData.linkedlin_url) - .field("githubUrl",testData.github_url) - .field("twitterUrl",testData.twitter_url) - .field("teams",testData.teams) - .attach('image',"./tests/utils/file.png",'file.png') - .then((res)=> { - id = res.body.result._id; - done(); - }) - .catch(done) - }); + // step 2 add team member to DB + it('Add team member at /teamMember/addTeamMember', (done) => { + const testData = { + full_name: 'Aman test', + description: 'This is for testing the api', + linkedlin_url: 'https//www.linkedin.in/AmanTest', + github_url: 'https/www.github.com/Aman16-ai', + twitter_url: 'https/www.tiwtter.com/Amanteset', + teams: ['Aman', 'anubhav'], + }; + chai + .request(server) + .post('/teamMember/addTeamMember') + .set('Authorization', `Bearer ${token}`) + .set('content-type', 'multipart/form-data') + .field('fullName', testData.full_name) + .field('description', testData.description) + .field('linkedlinUrl', testData.linkedlin_url) + .field('githubUrl', testData.github_url) + .field('twitterUrl', testData.twitter_url) + .field('teams', testData.teams) + .attach('image', './tests/utils/file.png', 'file.png') + .then((res) => { + id = res.body.result._id; + done(); + }) + .catch(done); + }); - //step 3 : delete team member from db - it("Deleting team member from DB",(done)=> { - chai - .request(server) - .delete('/teamMember/deleteTeamMember') - .set('Authorization', `Bearer ${token}`) - .send({memberId:id}) - .then((req)=> { - expect(req.body.message).to.equal("Deleted successfully"); - done(); - }) - .catch(done); - }) -}) \ No newline at end of file + // step 3 : delete team member from db + it('Deleting team member from DB', (done) => { + chai + .request(server) + .delete('/teamMember/deleteTeamMember') + .set('Authorization', `Bearer ${token}`) + .send({ memberId: id }) + .then((req) => { + expect(req.body.message).to.equal('Deleted successfully'); + done(); + }) + .catch(done); + }); +}); diff --git a/backend/tests/routes/teamMember/updateTeamMember.test.js b/backend/tests/routes/teamMember/updateTeamMember.test.js index 4d8ca6d5..2e10d1c8 100644 --- a/backend/tests/routes/teamMember/updateTeamMember.test.js +++ b/backend/tests/routes/teamMember/updateTeamMember.test.js @@ -2,90 +2,90 @@ const chai = require('chai'); const { expect } = require('chai'); const chaiHttp = require('chai-http'); const server = require('../../../index'); + chai.use(chaiHttp); -describe('update team member from DB',()=> { - let token = '' - let id = '' - //Step 1 : login as admin - it('log in as admin at /auth/login', (done) => { - const loginData = { - email: 'kajolkumarisingh222@gmail.com', - password: 'password', - }; - - chai - .request(server) - .post('/auth/login') - .send(loginData) - .then((res) => { - expect(res.status).to.equal(200); - expect(res.body.email).to.equal(loginData.email); - expect(res.body.isSuperAdmin).to.equal(true); - expect(res.body.token).to.be.a('string'); - token = res.body.token; - done(); - }) - .catch(done); - }); +describe('update team member from DB', () => { + let token = ''; + let id = ''; + // Step 1 : login as admin + it('log in as admin at /auth/login', (done) => { + const loginData = { + email: 'kajolkumarisingh222@gmail.com', + password: 'password', + }; + + chai + .request(server) + .post('/auth/login') + .send(loginData) + .then((res) => { + expect(res.status).to.equal(200); + expect(res.body.email).to.equal(loginData.email); + expect(res.body.isSuperAdmin).to.equal(true); + expect(res.body.token).to.be.a('string'); + token = res.body.token; + done(); + }) + .catch(done); + }); - //step 2 add team member to DB - it('Add team member at /teamMember/addTeamMember',(done)=> { - const testData = { - full_name : "Aman test", - description :"This is for testing the api" , - linkedlin_url : "https//www.linkedin.in/AmanTest", - github_url : "https/www.github.com/Aman16-ai", - twitter_url : "https/www.tiwtter.com/Amanteset", - teams: ["Aman","anubhav"] - } - chai - .request(server) - .post('/teamMember/addTeamMember') - .set('Authorization', `Bearer ${token}`) - .set('content-type','multipart/form-data') - .field("fullName",testData.full_name) - .field("description",testData.description) - .field("linkedlinUrl",testData.linkedlin_url) - .field("githubUrl",testData.github_url) - .field("twitterUrl",testData.twitter_url) - .field("teams",testData.teams) - .attach('image',"./tests/utils/file.png",'file.png') - .then((res)=> { - id = res.body.result._id; - done(); - }) - .catch(done) - }); + // step 2 add team member to DB + it('Add team member at /teamMember/addTeamMember', (done) => { + const testData = { + full_name: 'Aman test', + description: 'This is for testing the api', + linkedlin_url: 'https//www.linkedin.in/AmanTest', + github_url: 'https/www.github.com/Aman16-ai', + twitter_url: 'https/www.tiwtter.com/Amanteset', + teams: ['Aman', 'anubhav'], + }; + chai + .request(server) + .post('/teamMember/addTeamMember') + .set('Authorization', `Bearer ${token}`) + .set('content-type', 'multipart/form-data') + .field('fullName', testData.full_name) + .field('description', testData.description) + .field('linkedlinUrl', testData.linkedlin_url) + .field('githubUrl', testData.github_url) + .field('twitterUrl', testData.twitter_url) + .field('teams', testData.teams) + .attach('image', './tests/utils/file.png', 'file.png') + .then((res) => { + id = res.body.result._id; + done(); + }) + .catch(done); + }); - //step 3 : Updating team member - it("Updating team member from DB",(done)=> { - const testData = { - teamMemberId:id, - full_name : "Shubhamasdfadsfst", - description :"This is for testing the api" , - linkedlin_url : "https//www.linkedin.in/AmanTest", - github_url : "https/www.github.com/Aman16-ai", - twitter_url : "https/www.tiwtter.com/Amanteset", - teams: ["Aman","anubhav"] - } - chai - .request(server) - .put('/teamMember/updateTeamMember') - .set('Authorization', `Bearer ${token}`) - .set('content-type','multipart/form-data') - .field("teamMemberId",testData.teamMemberId) - .field("full_name",testData.full_name) - .field("description",testData.description) - .field("linkedin_url",testData.linkedlin_url) - .field("github_url",testData.github_url) - .field("twitter_url",testData.twitter_url) - .field("teams",testData.teams) - .attach('image',"./tests/utils/file2.png",'file2.png') - .end((err,res)=> { - expect(res.body.message).to.equal("updated successfully"); - done(); - }); - - }) -}) \ No newline at end of file + // step 3 : Updating team member + it('Updating team member from DB', (done) => { + const testData = { + teamMemberId: id, + full_name: 'Shubhamasdfadsfst', + description: 'This is for testing the api', + linkedlin_url: 'https//www.linkedin.in/AmanTest', + github_url: 'https/www.github.com/Aman16-ai', + twitter_url: 'https/www.tiwtter.com/Amanteset', + teams: ['Aman', 'anubhav'], + }; + chai + .request(server) + .put('/teamMember/updateTeamMember') + .set('Authorization', `Bearer ${token}`) + .set('content-type', 'multipart/form-data') + .field('teamMemberId', testData.teamMemberId) + .field('full_name', testData.full_name) + .field('description', testData.description) + .field('linkedin_url', testData.linkedlin_url) + .field('github_url', testData.github_url) + .field('twitter_url', testData.twitter_url) + .field('teams', testData.teams) + .attach('image', './tests/utils/file2.png', 'file2.png') + .end((err, res) => { + expect(res.body.message).to.equal('updated successfully'); + done(); + }); + }); +}); diff --git a/backend/utility/emailTemplates.js b/backend/utility/emailTemplates.js index caa5cbca..b7f3d04e 100644 --- a/backend/utility/emailTemplates.js +++ b/backend/utility/emailTemplates.js @@ -94,3 +94,15 @@ module.exports.ResourceDeletedMailTemplate = (adminName) => { `; return emailContent; }; + +module.exports.resetPasswordMailTemplate = (data) => { + const emailContent = ` +

Hello, ${data.adminName}

+ Click below link to reset your password
+ Reset password link +
+
+ Please ignore this mail If you not request the service + `; + return emailContent; +}; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 2d54db17..d578fed1 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -6555,6 +6555,11 @@ } } }, + "dompurify": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.6.tgz", + "integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==" + }, "domutils": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.7.0.tgz", diff --git a/frontend/src/pages/ForgotPassword/ForgotPassword.jsx b/frontend/src/pages/ForgotPassword/ForgotPassword.jsx index 7302d018..f58349fe 100644 --- a/frontend/src/pages/ForgotPassword/ForgotPassword.jsx +++ b/frontend/src/pages/ForgotPassword/ForgotPassword.jsx @@ -4,10 +4,23 @@ import { Button2 } from "../../components/util/Button/index"; import style from "./ForgotPassword.module.scss"; import Grid from "@material-ui/core/Grid"; import { Link } from "react-router-dom"; +import { SimpleToast } from "../../components/util/Toast"; +import axios from 'axios' +import {END_POINT} from '../../config/api' export function ForgotPassword(props) { const [status, setStatus] = useState(""); const [submited, setSubmited] = useState(false); + const [toast, setToast] = useState({ + open: false, + message: "", + severity: "" + }) + + const handleCloseToast = () => { + setToast({ open: false, message: "", severity: "" }) + } + let dark = props.theme; const [formdata, setFormData] = useState({ @@ -75,8 +88,20 @@ export function ForgotPassword(props) { setFormErrors(errors); }; - function submitForgotPassword(e) { - return setSubmited(true); + async function submitForgotPassword() { + setToast({open:true,message:"Loading...",severity:"info"}) + axios.post(`${END_POINT}/admin/forgotpassword`, { + email:formdata?.email + },{responseType:"json"}) + .then(function (res) { + setToast({open:true,message:"Reset mail sent",severity:"success"}); + setSubmited(true); + }) + .catch(function (error) { + setToast({open:true,message:"User not found",severity:"error"}) + setFormData({email:""}) + }); + return null } return ( @@ -189,6 +214,7 @@ export function ForgotPassword(props) { name="email" placeholder="Email" onChange={handleChange} + value={formdata.email} className={ dark ? `${style["input-forgot-password-dark"]} ${style["input-forgot-password"]}` @@ -227,6 +253,12 @@ export function ForgotPassword(props) { + ); diff --git a/frontend/src/pages/ForgotPasswordRecovery/ForgotPasswordRecovery.jsx b/frontend/src/pages/ForgotPasswordRecovery/ForgotPasswordRecovery.jsx index 26f9f061..d06a8e24 100644 --- a/frontend/src/pages/ForgotPasswordRecovery/ForgotPasswordRecovery.jsx +++ b/frontend/src/pages/ForgotPasswordRecovery/ForgotPasswordRecovery.jsx @@ -1,31 +1,37 @@ -import React, { useState } from "react"; +import React, { useEffect, useState } from "react"; import style from "./ForgotPasswordRecovery.module.scss"; import { Button2 } from "../../components/util/Button/index"; import { SimpleToast } from "../../components/util/Toast"; import Grid from "@material-ui/core/Grid"; -import { Link } from "react-router-dom"; +import { Link, useParams } from "react-router-dom"; +import axios from "axios"; +import { END_POINT } from "../../config/api"; export function ForgotPasswordRecovery() { const [new_password, setNewPassword] = useState(""); const [confirm_password, setConfirmPassword] = useState(""); const [openPasswordChanged, setPasswordChanged] = useState(false); + const[openPasswordChangeFailed,setPasswordChangeFailed]=useState(false) const [openUnmatchedPassword, setUnmatchedPassword] = useState(false); const [checkUpdatedPassword, setCheckUpdatedPassword] = useState(false); + const { id } = useParams() + + const handleCloseToast = (event, reason) => { if (reason === "clickaway") { return; } setPasswordChanged(false); setUnmatchedPassword(false); + setPasswordChangeFailed(false) }; function handleSubmit(e) { e.preventDefault(); if (new_password === confirm_password) { setNewPassword(""); setConfirmPassword(""); - setPasswordChanged(true); - setCheckUpdatedPassword(true); + handleResetPassword() } else { setUnmatchedPassword(true); setNewPassword(""); @@ -33,6 +39,21 @@ export function ForgotPasswordRecovery() { } } + async function handleResetPassword() { + axios.post(`${END_POINT}/admin/resetpassword/${id}`, { + newPassword: new_password + }, { responseType: "json" }) + .then(function (res) { + setPasswordChanged(true); + setCheckUpdatedPassword(true); + }) + .catch(function (error) { + setPasswordChangeFailed(true) + setNewPassword(""); + setConfirmPassword(""); + }); + } + return ( <>
@@ -40,9 +61,9 @@ export function ForgotPasswordRecovery() { className={`${style["forgot-password-recovery-image"]} ${style["child1"]}`} > Forgot-Password-Recovery-Illustration + src="./images/forgot-password.png" + alt="forgot-password-illustration" + />
+ ); }