diff --git a/.gitignore b/.gitignore index fb470e2..1f65317 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ -node_modules -frontend/node_modules/ -.env -utils/questions.json +node_modules +frontend/node_modules/ +.env +utils/questions.json utils/updatedData.json \ No newline at end of file diff --git a/README.md b/README.md index 52503cb..228e77c 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,27 @@ -# Backend for Abhedya - 2024 - -## 1. Clone the repo -```bash - git clone https://github.com/istenith/abhedya24-backend.git -``` - -## 2. Move into the dir -```bash - cd abhedya24-backend -``` - -## 3. Install the dependencies -```bash - npm install -``` - -## 4. Run the backend -```bash - nodemon index -``` -The backend is now live on port 5001 (or 5002 if that doesn't work) - -## 5. See SwaggerDocs of the API at -```bash -http://localhost:5001/doc -``` +# Backend for Abhedya - 2024 + +## 1. Clone the repo +```bash + git clone https://github.com/istenith/abhedya24-backend.git +``` + +## 2. Move into the dir +```bash + cd abhedya24-backend +``` + +## 3. Install the dependencies +```bash + npm install +``` + +## 4. Run the backend +```bash + nodemon index +``` +The backend is now live on port 5001 (or 5002 if that doesn't work) + +## 5. See SwaggerDocs of the API at +```bash +http://localhost:5001/doc +``` diff --git a/controllers/gameController.js b/controllers/gameController.js index 8550be2..ca9db0a 100644 --- a/controllers/gameController.js +++ b/controllers/gameController.js @@ -1,177 +1,177 @@ -const expressAsync = require("express-async-handler") -const Question = require("../modals/questionModal") -const User = require("../modals/userModal") -const bcrypt = require("bcrypt") - -const fetchQuestion = expressAsync(async(req, res) => { - console.log(`-------------------------------------------\nfetch route hitting`) - const decodedData = res.locals.decoded - console.log("the recieved data is: ", decodedData) - const username = decodedData.decryptedName - const user = await User.findOne({username}) - const currentLevel = user.currentLevelInt - - if (currentLevel > 15) { - res.status(201).json({msg: 'Completed Abhedya'}) - return - } else { - console.log(`----------------------Current user is----------\n`, user) - console.log(`----------------------Current level is----------\n`, currentLevel) - const question = await Question.findOne({level: user.currentLevelInt}) - console.log("Question is: ", question) - res.status(200).json({question}) - } - -}) - -const submitAnswer = expressAsync(async(req, res, next) => { - const username = res.locals.decoded.decryptedName - const user = await User.findOne({username}) - const currentQuestionNumber = user.currentLevelInt - const question = await Question.findOne({level: currentQuestionNumber}) - const {userAnswer} = req.body - - if (await bcrypt.compare(userAnswer, question.correctAnswer)) { - if (currentQuestionNumber == 15) { - res.status(201).json({msg: "Completed."}) - user.currentLevelInt = 16 - const currentTimeStamp = Date.now() - const timeTakenForThisLevel = currentTimeStamp - user.prevQuestionTimeStamp - user.timeCompletedInSeconds.push(timeTakenForThisLevel) - await user.save() - return - } - const userCurrentLvl = user.currentLevelInt - const nextLevelInt = userCurrentLvl + 1 - const currentTimeStamp = Date.now() - const timeTakenForThisLevel = currentTimeStamp - user.prevQuestionTimeStamp - user.timeCompletedInSeconds.push(timeTakenForThisLevel) - await user.save() - // console.log("Correct Answer! You move on to the next question level") - const updatedUser = await User.findByIdAndUpdate( - user._id, - { - $set: { currentLevelInt: nextLevelInt }, - $push: { levelsCompleted: userCurrentLvl } - }, - { new: true } // This option returns the modified document rather than the original one - ); - // console.log("updated user is: ", updatedUser) - - // returning the next question back to the UI - const nextQuestion = await Question.findOne({level: currentQuestionNumber+1}) - res.status(200).json(nextQuestion) - next() - }else{ - console.log("Wrong Answer! Try again.") - res.status(400).send("Error wrong answer") - } -}) - -const updateLeaderboard = expressAsync(async(req, res) => { - - const compareTimes = (userOne, userTwo) => { - - if (userOne.currentLevelInt != userTwo.currentLevelInt) { - return userTwo.currentLevelInt - userOne.currentLevelInt - } - const userOneTotalTime = userOne.timeCompletedInSeconds.reduce((a,b) => a + b, 0) - const userTwoTotalTime = userTwo.timeCompletedInSeconds.reduce((a,b) => a + b, 0) - - if (userTwoTotalTime > userOneTotalTime) { - return -1 - } - if (userTwoTotalTime < userOneTotalTime){ - return 1 - } - return 0 - } - - - console.log("-------------------------------------------------------Updating Leaderboard--------------------------------\n") - - - const users = await User.find({startedAbhedya: true}).sort({currentLevelInt: -1}) - console.log(users) - - console.log('-----------------these were all users-----------------------------') - - users.sort(compareTimes) - - const deadUsers = await User.find({startedAbhedya: false}) - - const sortedUsers = [...users, ...deadUsers] - - console.log('Leaderboard: ', sortedUsers) - - res.status(200).json({sortedUsers}) - console.log("updated leaderboard!") - -}) - -const insertSampleData = expressAsync(async(req, res) => { - const data = req.body - console.log('recieved data') - - for (const [index, value] of data.entries()) { - console.log('current question is: ', value) - const question = new Question(value) - await question.save() - console.log("saved question no.", index+1) - } - res.status(200).json({sucess: "something"}) - -}) - -// const leaderBoard = expressAsync(async(req, res) => { -// const users = await User.find().sort({currentLevelInt: -1, timeCompletedInSeconds -// }) - -const manageQuestions = expressAsync(async(req, res) => { - const levels = await Question.find().lean() - let uniqueIdentifier - - switch (req.method) { - case "GET": - console.log("All questions are: ", levels) - res.status(200).json({levels: levels}) - break - case "POST": - const data = [req.body] - console.log('recieved data', data) - - for (const [index, value] of data.entries()) { - const question = new Question(value) - await question.save() - console.log("saved question no.", index+1) - } - res.status(200) - break - case "PUT": - - if (req.body.uniqueIdentifier) { - uniqueIdentifier = req.body.uniqueIdentifier - const {objectifiedData} = req.body - - const existingQuestion = await Question.findOne({questionId: uniqueIdentifier}) - const updatedQuestion = await Question.findByIdAndUpdate(existingQuestion._id, objectifiedData, {new: true}) - console.log("updated question: ", updatedQuestion) - res.status(200).send(`updated question: ${updatedQuestion}`) - } - break - case "DELETE": - if (req.body.uniqueIdentifier) { - uniqueIdentifier = req.body.uniqueIdentifier - - const questionToDelete = await Question.findOne({questionId: uniqueIdentifier}) - const question = await Question.findByIdAndDelete(questionToDelete._id) - console.log("question deleted: ", question) - res.status(200).send(`question deleted: ${question}`) - } - break - default: - res.status(400).send(`KYA KARRA BC METHOD HI GALAT HAI TUMHARA`) - } -}) - +const expressAsync = require("express-async-handler") +const Question = require("../modals/questionModal") +const User = require("../modals/userModal") +const bcrypt = require("bcrypt") + +const fetchQuestion = expressAsync(async(req, res) => { + console.log(`-------------------------------------------\nfetch route hitting`) + const decodedData = res.locals.decoded + console.log("the recieved data is: ", decodedData) + const username = decodedData.decryptedName + const user = await User.findOne({username}) + const currentLevel = user.currentLevelInt + + if (currentLevel > 15) { + res.status(201).json({msg: 'Completed Abhedya'}) + return + } else { + console.log(`----------------------Current user is----------\n`, user) + console.log(`----------------------Current level is----------\n`, currentLevel) + const question = await Question.findOne({level: user.currentLevelInt}) + console.log("Question is: ", question) + res.status(200).json({question}) + } + +}) + +const submitAnswer = expressAsync(async(req, res, next) => { + const username = res.locals.decoded.decryptedName + const user = await User.findOne({username}) + const currentQuestionNumber = user.currentLevelInt + const question = await Question.findOne({level: currentQuestionNumber}) + const {userAnswer} = req.body + + if (await bcrypt.compare(userAnswer, question.correctAnswer)) { + if (currentQuestionNumber == 15) { + res.status(201).json({msg: "Completed."}) + user.currentLevelInt = 16 + const currentTimeStamp = Date.now() + const timeTakenForThisLevel = currentTimeStamp - user.prevQuestionTimeStamp + user.timeCompletedInSeconds.push(timeTakenForThisLevel) + await user.save() + return + } + const userCurrentLvl = user.currentLevelInt + const nextLevelInt = userCurrentLvl + 1 + const currentTimeStamp = Date.now() + const timeTakenForThisLevel = currentTimeStamp - user.prevQuestionTimeStamp + user.timeCompletedInSeconds.push(timeTakenForThisLevel) + await user.save() + // console.log("Correct Answer! You move on to the next question level") + const updatedUser = await User.findByIdAndUpdate( + user._id, + { + $set: { currentLevelInt: nextLevelInt }, + $push: { levelsCompleted: userCurrentLvl } + }, + { new: true } // This option returns the modified document rather than the original one + ); + // console.log("updated user is: ", updatedUser) + + // returning the next question back to the UI + const nextQuestion = await Question.findOne({level: currentQuestionNumber+1}) + res.status(200).json(nextQuestion) + next() + }else{ + console.log("Wrong Answer! Try again.") + res.status(400).send("Error wrong answer") + } +}) + +const updateLeaderboard = expressAsync(async(req, res) => { + + const compareTimes = (userOne, userTwo) => { + + if (userOne.currentLevelInt != userTwo.currentLevelInt) { + return userTwo.currentLevelInt - userOne.currentLevelInt + } + const userOneTotalTime = userOne.timeCompletedInSeconds.reduce((a,b) => a + b, 0) + const userTwoTotalTime = userTwo.timeCompletedInSeconds.reduce((a,b) => a + b, 0) + + if (userTwoTotalTime > userOneTotalTime) { + return -1 + } + if (userTwoTotalTime < userOneTotalTime){ + return 1 + } + return 0 + } + + + console.log("-------------------------------------------------------Updating Leaderboard--------------------------------\n") + + + const users = await User.find({startedAbhedya: true}).sort({currentLevelInt: -1}) + console.log(users) + + console.log('-----------------these were all users-----------------------------') + + users.sort(compareTimes) + + const deadUsers = await User.find({startedAbhedya: false}) + + const sortedUsers = [...users, ...deadUsers] + + console.log('Leaderboard: ', sortedUsers) + + res.status(200).json({sortedUsers}) + console.log("updated leaderboard!") + +}) + +const insertSampleData = expressAsync(async(req, res) => { + const data = req.body + console.log('recieved data') + + for (const [index, value] of data.entries()) { + console.log('current question is: ', value) + const question = new Question(value) + await question.save() + console.log("saved question no.", index+1) + } + res.status(200).json({sucess: "something"}) + +}) + +// const leaderBoard = expressAsync(async(req, res) => { +// const users = await User.find().sort({currentLevelInt: -1, timeCompletedInSeconds +// }) + +const manageQuestions = expressAsync(async(req, res) => { + const levels = await Question.find().lean() + let uniqueIdentifier + + switch (req.method) { + case "GET": + console.log("All questions are: ", levels) + res.status(200).json({levels: levels}) + break + case "POST": + const data = [req.body] + console.log('recieved data', data) + + for (const [index, value] of data.entries()) { + const question = new Question(value) + await question.save() + console.log("saved question no.", index+1) + } + res.status(200) + break + case "PUT": + + if (req.body.uniqueIdentifier) { + uniqueIdentifier = req.body.uniqueIdentifier + const {objectifiedData} = req.body + + const existingQuestion = await Question.findOne({questionId: uniqueIdentifier}) + const updatedQuestion = await Question.findByIdAndUpdate(existingQuestion._id, objectifiedData, {new: true}) + console.log("updated question: ", updatedQuestion) + res.status(200).send(`updated question: ${updatedQuestion}`) + } + break + case "DELETE": + if (req.body.uniqueIdentifier) { + uniqueIdentifier = req.body.uniqueIdentifier + + const questionToDelete = await Question.findOne({questionId: uniqueIdentifier}) + const question = await Question.findByIdAndDelete(questionToDelete._id) + console.log("question deleted: ", question) + res.status(200).send(`question deleted: ${question}`) + } + break + default: + res.status(400).send(`KYA KARRA BC METHOD HI GALAT HAI TUMHARA`) + } +}) + module.exports = {fetchQuestion, submitAnswer, updateLeaderboard, insertSampleData, manageQuestions} \ No newline at end of file diff --git a/controllers/userController.js b/controllers/userController.js index 20e4fc1..7760f0b 100644 --- a/controllers/userController.js +++ b/controllers/userController.js @@ -1,233 +1,233 @@ -const nodemailer = require('nodemailer'); -const expressAsync = require('express-async-handler') -const User = require('../modals/userModal'); -const CryptoJS = require('crypto-js'); -const base64url = require('base64url'); -const jwt = require('jsonwebtoken'); -const bcrypt = require('bcrypt'); -const Queue = require('bull') - -const superUserController = expressAsync(async (req, res) => { - console.log("superUserContrller called.") - const {superusername, supassword} = res.locals.superuserData - console.log(`name: ${superusername}\npswd: ${supassword}`) - res.status(200) -}) - -// loggin in superuser -const superUserLogin = expressAsync(async (req, res) => { - console.log("login module called.") - const { superusername, supassword } = req.body - - console.log("recieved: ", superusername, supassword) - const superUserinDb = await User.findOne({type: 0, username: superusername}).lean() - - if (superUserinDb) { - console.log("superUserFound") - - if (await bcrypt.compare(supassword, superUserinDb.password)) { - console.log("password verified\nReturning JWT token...\n", superusername, supassword) - - const loginToken = jwt.sign({ - superuser: true, - username: superusername, - password: supassword - }, process.env.SECRET) - - res.status(200).send(loginToken) - console.log("returned JWT token. User verified.") - }else{ - console.log("wrong password") - res.status(401).send("Wrong password!") - } - - } else { - console.log("super user not found") - res.status(404).send("Super user not found") - } -}) - -// managing users for the superuser profile -const manageUsers = expressAsync(async (req, res) => { - - let uniqueIdentifier; - - switch (req.method) { - case 'GET': - const users = await User.find() - console.log("all users are\n", users) - res.status(200).json({users: users}) - break - case 'PUT': - if (req.body.uniqueIdentifier){ - uniqueIdentifier = req.body.uniqueIdentifier - const {objectifiedData} = req.body - console.log("the updated user you sent is this: ", uniqueIdentifier, objectifiedData) - - // finding and replacing the data - const existingUser = await User.findOne({username: uniqueIdentifier}) - console.log("existingUser", existingUser) - const updatedUser = await User.findByIdAndUpdate(existingUser._id, objectifiedData, {new: true}) - console.log('updated ', updatedUser) - res.status(200).send(`updated user: ${updatedUser}`) - } - break - case "DELETE": - console.log("entered deletion module") - if (req.body.uniqueIdentifier){ - uniqueIdentifier = req.body.uniqueIdentifier - console.log("found identifier: ", uniqueIdentifier) - console.log("The user to delete is: ", uniqueIdentifier) - const user = await User.findOne({username: uniqueIdentifier}) - const deletedUser = await User.findByIdAndDelete(user._id) - res.status(200).send(`The user to delete is ${user}`) - } else { - console.log("wtf bhai data hi nahi aaya") - } - break - case 'POST': - const {newUserToAdd} = req.body - console.log("Th enew user to add is: ", newUserToAdd) - res.status(200).send(`The new user to add is: ${newUserToAdd}`) - break - default: - res.status(400).send(`Invalid request type`) - } - console.log("Exiting managing users...") -}) - -const registerUser = expressAsync(async (req, res) => { - console.log("register user called") - const {username, email, firstName, lastName} = req.body - - // const emailRegex = (emailToTest) => { - // // Regular expression pattern for the specified format - // const pattern = /^[0-9]{2}[a-zA-Z]{3}[0-9]{3}@nith\.ac\.in$/; - - // // Test the email against the pattern - // return pattern.test(emailToTest); - // } - - // if (!emailRegex(email)) { - // res.status(422).json({err: 'enter college email'}) - // return - // } - - const encryptText = (text, key) => { - const encrypted = CryptoJS.AES.encrypt(text, key); - return encrypted.toString(); - }; - - // secret key - const secretKey = 'prodyabhedya'; - // the encrypted string - const encryptedLink = base64url(encryptText(username, secretKey)) - - console.log('Data received: ', username, email, firstName, lastName) - - if (!username || !email) { - res.status(400) - } - - let possibleUserByEmail = await User.findOne({email}) - let possibleUserByUsername = await User.findOne({username}) - - if(!possibleUserByEmail && !possibleUserByUsername) { - console.log("New user") - const user = await User({username, email, firstName, lastName, loginLink: encryptedLink}) - console.log('user created') - console.log({username, email, firstName, lastName}) - await user.save() - res.status(200).json({msg: 'registered'}) - console.log(`User ${username} created successfully.`) - }else if(possibleUserByUsername) { - res.status(421).json({msg: "Username taken"}) - return - }else{ - console.log("Existing user.") - res.status(400).json({msg: 'already exists'}) - returnstart - } - -}) - -const validateLinkAndLogin = expressAsync(async(req, res) => { - console.log("login asked for user", req.params.encryptedUsername) - const encryptedName = base64url.decode(req.params.encryptedUsername) - const decryptText = (encryptedName, key) => { - const decrypted = CryptoJS.AES.decrypt(encryptedName, key); - return decrypted.toString(CryptoJS.enc.Utf8); - }; - - const secretKey = "prodyabhedya" - const decryptedName = decryptText(encryptedName, secretKey); - console.log('Decrypted:', decryptedName); - - - const user = await User.findOne({username: decryptedName}) - - if (user) { - console.log('user found') - const loginToken = jwt.sign( - {decryptedName}, - process.env.SECRET, - ) - - console.log('login token generated: ', loginToken) - res.status(200).json({loginToken, startedAbhedya: user.startedAbhedya}) - } else { - console.log("User not found") - res.status(404).json({Error: `You haven't registered for Abhedya2k24 yet. Follow this link to register http://localhost:3000/user/register/`}) - } -}) - -const startAbhedya = expressAsync(async (req, res) => { - const decodedData = res.locals.decoded //coming from the middleware. Contains username and iat. - const username = decodedData.decryptedName - const currentUser = await User.findOne({username}) - - currentUser.startedAbhedya = true - currentUser.prevQuestionTimeStamp = Date.now() - - try{ - await currentUser.save() - res.status(200).json({msg: 'user started abhedya'}) - } catch { - e => console.log(e) - } - -}) - -const resendLink = expressAsync(async(req,res)=>{ - const {email}=req.body - console.log(email); - - const currentUser= await User.findOne({email}); - - if(currentUser){ - const change = await User.findOneAndUpdate({email:email},{emailSent:false}) - res.status(200).json({msg:"Successfylly sent email"}) - console.log(change.emailSent); - } - else{ - res.status(402).json({Err:"User not found"}) - } - - -}) - - -const userDetails = expressAsync(async(req, res) => { - const decodedData = res.locals.decoded //coming from the middleware. Contains username and iat. - const username = decodedData.decryptedName - const currentUser = await User.findOne({username}) - - if (currentUser) { - res.status(200).json({startedAbhedya: currentUser.startedAbhedya}) - } else { - res.status(404).json({Err: 'User not found in the database'}) - } -}) - - +const nodemailer = require('nodemailer'); +const expressAsync = require('express-async-handler') +const User = require('../modals/userModal'); +const CryptoJS = require('crypto-js'); +const base64url = require('base64url'); +const jwt = require('jsonwebtoken'); +const bcrypt = require('bcrypt'); +const Queue = require('bull') + +const superUserController = expressAsync(async (req, res) => { + console.log("superUserContrller called.") + const {superusername, supassword} = res.locals.superuserData + console.log(`name: ${superusername}\npswd: ${supassword}`) + res.status(200) +}) + +// loggin in superuser +const superUserLogin = expressAsync(async (req, res) => { + console.log("login module called.") + const { superusername, supassword } = req.body + + console.log("recieved: ", superusername, supassword) + const superUserinDb = await User.findOne({type: 0, username: superusername}).lean() + + if (superUserinDb) { + console.log("superUserFound") + + if (await bcrypt.compare(supassword, superUserinDb.password)) { + console.log("password verified\nReturning JWT token...\n", superusername, supassword) + + const loginToken = jwt.sign({ + superuser: true, + username: superusername, + password: supassword + }, process.env.SECRET) + + res.status(200).send(loginToken) + console.log("returned JWT token. User verified.") + }else{ + console.log("wrong password") + res.status(401).send("Wrong password!") + } + + } else { + console.log("super user not found") + res.status(404).send("Super user not found") + } +}) + +// managing users for the superuser profile +const manageUsers = expressAsync(async (req, res) => { + + let uniqueIdentifier; + + switch (req.method) { + case 'GET': + const users = await User.find() + console.log("all users are\n", users) + res.status(200).json({users: users}) + break + case 'PUT': + if (req.body.uniqueIdentifier){ + uniqueIdentifier = req.body.uniqueIdentifier + const {objectifiedData} = req.body + console.log("the updated user you sent is this: ", uniqueIdentifier, objectifiedData) + + // finding and replacing the data + const existingUser = await User.findOne({username: uniqueIdentifier}) + console.log("existingUser", existingUser) + const updatedUser = await User.findByIdAndUpdate(existingUser._id, objectifiedData, {new: true}) + console.log('updated ', updatedUser) + res.status(200).send(`updated user: ${updatedUser}`) + } + break + case "DELETE": + console.log("entered deletion module") + if (req.body.uniqueIdentifier){ + uniqueIdentifier = req.body.uniqueIdentifier + console.log("found identifier: ", uniqueIdentifier) + console.log("The user to delete is: ", uniqueIdentifier) + const user = await User.findOne({username: uniqueIdentifier}) + const deletedUser = await User.findByIdAndDelete(user._id) + res.status(200).send(`The user to delete is ${user}`) + } else { + console.log("wtf bhai data hi nahi aaya") + } + break + case 'POST': + const {newUserToAdd} = req.body + console.log("Th enew user to add is: ", newUserToAdd) + res.status(200).send(`The new user to add is: ${newUserToAdd}`) + break + default: + res.status(400).send(`Invalid request type`) + } + console.log("Exiting managing users...") +}) + +const registerUser = expressAsync(async (req, res) => { + console.log("register user called") + const {username, email, firstName, lastName} = req.body + + // const emailRegex = (emailToTest) => { + // // Regular expression pattern for the specified format + // const pattern = /^[0-9]{2}[a-zA-Z]{3}[0-9]{3}@nith\.ac\.in$/; + + // // Test the email against the pattern + // return pattern.test(emailToTest); + // } + + // if (!emailRegex(email)) { + // res.status(422).json({err: 'enter college email'}) + // return + // } + + const encryptText = (text, key) => { + const encrypted = CryptoJS.AES.encrypt(text, key); + return encrypted.toString(); + }; + + // secret key + const secretKey = 'prodyabhedya'; + // the encrypted string + const encryptedLink = base64url(encryptText(username, secretKey)) + + console.log('Data received: ', username, email, firstName, lastName) + + if (!username || !email) { + res.status(400) + } + + let possibleUserByEmail = await User.findOne({email}) + let possibleUserByUsername = await User.findOne({username}) + + if(!possibleUserByEmail && !possibleUserByUsername) { + console.log("New user") + const user = await User({username, email, firstName, lastName, loginLink: encryptedLink}) + console.log('user created') + console.log({username, email, firstName, lastName}) + await user.save() + res.status(200).json({msg: 'registered'}) + console.log(`User ${username} created successfully.`) + }else if(possibleUserByUsername) { + res.status(421).json({msg: "Username taken"}) + return + }else{ + console.log("Existing user.") + res.status(400).json({msg: 'already exists'}) + returnstart + } + +}) + +const validateLinkAndLogin = expressAsync(async(req, res) => { + console.log("login asked for user", req.params.encryptedUsername) + const encryptedName = base64url.decode(req.params.encryptedUsername) + const decryptText = (encryptedName, key) => { + const decrypted = CryptoJS.AES.decrypt(encryptedName, key); + return decrypted.toString(CryptoJS.enc.Utf8); + }; + + const secretKey = "prodyabhedya" + const decryptedName = decryptText(encryptedName, secretKey); + console.log('Decrypted:', decryptedName); + + + const user = await User.findOne({username: decryptedName}) + + if (user) { + console.log('user found') + const loginToken = jwt.sign( + {decryptedName}, + process.env.SECRET, + ) + + console.log('login token generated: ', loginToken) + res.status(200).json({loginToken, startedAbhedya: user.startedAbhedya}) + } else { + console.log("User not found") + res.status(404).json({Error: `You haven't registered for Abhedya2k24 yet. Follow this link to register http://localhost:3000/user/register/`}) + } +}) + +const startAbhedya = expressAsync(async (req, res) => { + const decodedData = res.locals.decoded //coming from the middleware. Contains username and iat. + const username = decodedData.decryptedName + const currentUser = await User.findOne({username}) + + currentUser.startedAbhedya = true + currentUser.prevQuestionTimeStamp = Date.now() + + try{ + await currentUser.save() + res.status(200).json({msg: 'user started abhedya'}) + } catch { + e => console.log(e) + } + +}) + +const resendLink = expressAsync(async(req,res)=>{ + const {email}=req.body + console.log(email); + + const currentUser= await User.findOne({email}); + + if(currentUser){ + const change = await User.findOneAndUpdate({email:email},{emailSent:false}) + res.status(200).json({msg:"Successfylly sent email"}) + console.log(change.emailSent); + } + else{ + res.status(402).json({Err:"User not found"}) + } + + +}) + + +const userDetails = expressAsync(async(req, res) => { + const decodedData = res.locals.decoded //coming from the middleware. Contains username and iat. + const username = decodedData.decryptedName + const currentUser = await User.findOne({username}) + + if (currentUser) { + res.status(200).json({startedAbhedya: currentUser.startedAbhedya}) + } else { + res.status(404).json({Err: 'User not found in the database'}) + } +}) + + module.exports = {startAbhedya, registerUser, validateLinkAndLogin, superUserController, manageUsers, superUserLogin, userDetails ,resendLink} \ No newline at end of file diff --git a/database/connection.js b/database/connection.js index 2ae2f7b..e075204 100644 --- a/database/connection.js +++ b/database/connection.js @@ -1,12 +1,12 @@ -const mongoose = require('mongoose'); - -const connectToDb = async () => { - try{ - const connect = await mongoose.connect(process.env.CONN) - console.log(`Connection established ${connect.connection.name} on ${connect.connection.port}`) - }catch(e){ - console.log("error hogya: ", e) - } -} - +const mongoose = require('mongoose'); + +const connectToDb = async () => { + try{ + const connect = await mongoose.connect(process.env.CONN) + console.log(`Connection established ${connect.connection.name} on ${connect.connection.port}`) + }catch(e){ + console.log("error hogya: ", e) + } +} + module.exports = connectToDb \ No newline at end of file diff --git a/frontend/app/admin/components/Model.jsx b/frontend/app/admin/components/Model.jsx index ba9c9f8..6b3deac 100644 --- a/frontend/app/admin/components/Model.jsx +++ b/frontend/app/admin/components/Model.jsx @@ -1,140 +1,140 @@ -import React, { useEffect, useState } from 'react' -import axios from 'axios' -import Cookies from 'js-cookie' -import ModifyForm from './ModifyForm' - -const Model = (params) => { - const token = Cookies.get("token") - const [dataList, setDataList] = useState([]) - const [userAction, setuserAction] = useState('') - - const headers = { - Authorization: "Bearer " + token - } - - useEffect(() => { - console.log("dataType is: ", params.dataType) - const fetchData = async () => { - await axios.get(`http://localhost:5001/user/superuser/${params.dataType}/`, {headers}) - .then((response) => { - console.log("response: ", response.data[params.dataType]) - setDataList(response.data[params.dataType]) - }) - } - fetchData() - }, [params.dataType]) - - const handleUserAction = (action) => { - setuserAction(action) - } - - - let tableData = [] - - switch (params.dataType) { - case 'users': - for (const data of dataList) { - if (data.type == 1) { - tableData.push( - - {dataList.indexOf(data) + 1}. - {data.username} - {data.currentLevelInt} - - ) - } - } - break - case 'levels': - for (const data of dataList) { - tableData.push( - - {data.level} - {data.questionId} - {data.questionTitle} - {data.correctAnswer} - - ) - } - break - - } - - return( -
-
-
- - - - -
- - {/* the form actions */} - { - (()=>{ - switch(userAction) { - case 'add': - return( - - ) - case 'modify': - return( - - ) - case 'delete': - return( - - ) - default: - return( -

Nothing to do...

- ) - } - })() - } - -
- - - - - - - {params.dataType === 'levels' && } - - - - {tableData} - -
- {(()=>{ - if(params.dataType === 'users'){ - return('S.no') - }else{ - return('Level') - } - })()} - - {(()=>{ - if(params.dataType === 'users') { - return('Username') - } else { - return('Question ID') - } - })()} - - {(()=>{ - if(params.dataType === 'users') { - return('Level') - } else { - return('Question') - } - })()} - Correct Answer
-
- ) - -} - -export default Model +import React, { useEffect, useState } from 'react' +import axios from 'axios' +import Cookies from 'js-cookie' +import ModifyForm from './ModifyForm' + +const Model = (params) => { + const token = Cookies.get("token") + const [dataList, setDataList] = useState([]) + const [userAction, setuserAction] = useState('') + + const headers = { + Authorization: "Bearer " + token + } + + useEffect(() => { + console.log("dataType is: ", params.dataType) + const fetchData = async () => { + await axios.get(`http://localhost:5001/user/superuser/${params.dataType}/`, {headers}) + .then((response) => { + console.log("response: ", response.data[params.dataType]) + setDataList(response.data[params.dataType]) + }) + } + fetchData() + }, [params.dataType]) + + const handleUserAction = (action) => { + setuserAction(action) + } + + + let tableData = [] + + switch (params.dataType) { + case 'users': + for (const data of dataList) { + if (data.type == 1) { + tableData.push( + + {dataList.indexOf(data) + 1}. + {data.username} + {data.currentLevelInt} + + ) + } + } + break + case 'levels': + for (const data of dataList) { + tableData.push( + + {data.level} + {data.questionId} + {data.questionTitle} + {data.correctAnswer} + + ) + } + break + + } + + return( +
+
+
+ + + + +
+ + {/* the form actions */} + { + (()=>{ + switch(userAction) { + case 'add': + return( + + ) + case 'modify': + return( + + ) + case 'delete': + return( + + ) + default: + return( +

Nothing to do...

+ ) + } + })() + } + +
+ + + + + + + {params.dataType === 'levels' && } + + + + {tableData} + +
+ {(()=>{ + if(params.dataType === 'users'){ + return('S.no') + }else{ + return('Level') + } + })()} + + {(()=>{ + if(params.dataType === 'users') { + return('Username') + } else { + return('Question ID') + } + })()} + + {(()=>{ + if(params.dataType === 'users') { + return('Level') + } else { + return('Question') + } + })()} + Correct Answer
+
+ ) + +} + +export default Model diff --git a/frontend/app/admin/components/ModifyForm.jsx b/frontend/app/admin/components/ModifyForm.jsx index 651195d..4a429ce 100644 --- a/frontend/app/admin/components/ModifyForm.jsx +++ b/frontend/app/admin/components/ModifyForm.jsx @@ -1,199 +1,199 @@ -'use client' -import { useState } from 'react' -import React from 'react' -import axios from 'axios' -import { useRouter } from 'next/navigation' -import Cookies from 'js-cookie' - -const ModifyhtmlForm = ({type, dataModal}) => { - const router = useRouter() - const [uniqueIdentifier, setUniqueIdentifier] = useState('') - const [newValue, setNewValue] = useState('') - - // the source token of axios instance, required to close the instance when reloading the page - const source = axios.CancelToken.source() - - // creating an instance for using axios - const token = Cookies.get("token") - const axiosInstance = axios.create({ - baseURL: 'http://localhost:5001/user/superuser/', - headers: { - 'Authorization': "Bearer " + token - }, - cancelToken: source.token - }) - - - const handleClickApiRequests = async (dataModal, reqType) => { - alert(`new value: ${newValue}\nIdentifier: ${uniqueIdentifier}`) - - let objectifiedData = {} - if(newValue){ - objectifiedData = JSON.parse(newValue) - } - // checking the type of request - switch (reqType) { - case 'add': - // Checking the data model - if (dataModal === 'users') { - console.log(objectifiedData) - await axios.post('http://localhost:5001/user/register/', objectifiedData, {headers: {'Authorization': 'Bearer ' + token}}) - .then((response) =>{ - response.status===200 ? - (alert("registered!"), alert(response.data.msg)) - : - (alert("maa chud gyi")) - - if (response.status===400) { - alert(response.data.error) - } else if (response.status===404){ - alert("nahi mila") - } - }) - .finally(()=> { - router.refresh() - }) - - - } else if(dataModal === 'levels') { - console.log(objectifiedData) - - try { - // using in try catch block - await axiosInstance.post('/levels/', objectifiedData) - .then((response) =>{ - response.status===200 ? - alert("added level!") - : - alert("maa chud gyi") - - if (response.status===400) { - alert(response.data.error) - } else if (response.status===404){ - alert("nahi mila") - } - }) - .finally(()=> { - router.refresh() - }) - } catch (error) { - if (axios.isAxiosError(error)) { - // The error is an AxiosError (specific to Axios) - console.error('Axios Error:', error.message) - } else { - // Other types of errors - console.error('Error:', error.message) - } - } - } - break - case 'modify': - // modifying data model - - - // Checking the data model - if (dataModal === 'users') { - // console.log('identifier: ', uniqueIdentifier) - // console.log('newValue: ', newValue) - - await axiosInstance.put("/users/", {uniqueIdentifier, objectifiedData}) - .then((response) => { - alert(response.data) - }) - .finally(()=>{ - alert("okay") - }) - } else { - await axiosInstance.put("/levels/", {uniqueIdentifier, objectifiedData}) - .then((response) => { - alert(response.data) - }) - .finally(()=>{ - alert("okay") - }) - } - break - case 'delete': - // Checking the data model - if (dataModal === 'users') { - alert("wanna delete??? mmmhmm") - alert(`Unique Identifier: ${uniqueIdentifier}\nIts type is: ${typeof(uniqueIdentifier)}`) - await axiosInstance.delete("/users/", { - data: { - uniqueIdentifier: uniqueIdentifier - } - }) - .then((response) => { - alert("response aagya") - alert(response.data) - }) - .finally(()=>{ - alert("kardiya delete") - }) - } else { - alert("wanna delete question??? mmhmhmm") - await axiosInstance.delete("/levels/", { - data: { - uniqueIdentifier: uniqueIdentifier - } - }) - .then((response)=>{ - alert(response.data) - }) - .finally(()=>{ - alert("kardiya level delete") - }) - } - break - default: - alert("bc kya karra hai") - } - } - - - - if (type === 'modify') { - return ( -
- - setUniqueIdentifier(e.target.value)} - value={uniqueIdentifier} - /> - -