Skip to content

Commit

Permalink
test readme update, signup route fix
Browse files Browse the repository at this point in the history
  • Loading branch information
manupanand committed Nov 11, 2024
1 parent 7f5ec39 commit 1df5c76
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 113 deletions.
13 changes: 7 additions & 6 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,14 @@ jobs:

- run: |
npm ci
echo "${{ secrets.PROD_ENV_FILE }}" > .env
pm2 stop quizapp || true
pm2 delete quizapp || true
pm2 kill
npm install
pm2 start /home/ubuntu/actions-runner/_work/project-quiz-app/project-quiz-app/src/index.js --name "quizapp" || pm2 restart "quizapp"
pm2 save
# echo "${{ secrets.PROD_ENV_FILE }}" > .env
# pm2 stop quizapp || true
# pm2 delete quizapp || true
# pm2 kill
# pm2 start /home/ubuntu/actions-runner/_work/project-quiz-app/project-quiz-app/src/index.js --name "quizapp" || pm2 restart "quizapp"
#pm2 save
# # Ensure dependencies are up-to-date
# npm ci
Expand Down
60 changes: 52 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,32 @@
# Quiz Application

This is a simple quiz application built using Node.js and Express. It provides a platform for users to take quizzes and view their results.
Features
This project is a backend application for a quiz platform, allowing users to register, log in, and answer questions in a quiz format. The backend is implemented with Node.js, MongoDB, and it includes user authentication, token management.

User-friendly Interface: Easy-to-navigate quiz format.
Timed Questions: Option to add time limits to questions.
Score Calculation: Automatically calculates and displays the score upon quiz completion.
### Project Structure

- routes: Contains application routes.
- controllers: Contains logic for handling quiz data.
- models: Defines data structure (if using a database).
- middleware: Middleware functions for request processing.
- config: Contains utility functions and configurations for the project.

### Features

- User Authentication: Allows users to sign in, and admins can also log in with specific privileges.
- Token Management: Uses JSON Web Tokens (JWT) for user authentication and Redis for session management.
- Quiz Functionality: CRUD operations for questions and answers, with role-based access (admin, user).
- Data Storage: MongoDB for storing user and quiz data, Redis for caching session tokens.

### Technologies

- Backend: Node.js, Express
- Database: MongoDB (Mongoose)
- Token Management: JSON Web Tokens (JWT)
- Logging: Custom logging using Winston
- Encrypt/Decrypt using crypto-js

### Prerequisites

Expand All @@ -26,6 +47,16 @@ cd project-quiz-app
```
npm install
```
### Set up environment variables:
Create a .env file in the root directory and configure the following:

```
-MONGO_ATLAS="mongodb://localhost:27017/testdb"
-MONGO_ATLAS= your mongo atlas url
-ENCRYPT_SECRET_KEY=
-JWT_SECRET_KEY=
```


### Running the Application

Expand All @@ -36,14 +67,27 @@ npm run server
```

This will launch the application at http://localhost:3000 by default.
This will launch the application at http://localhost:2500 by default.

### Project Structure
Usage
API Endpoints

User Authentication:
POST /user/signin - Sign in as a regular user
POST /admin/signin -Sign in as a regular admin.
POST /admin/signup - Sign up as a new admin.
POST /user/signup -Signup in as a regular user
Quiz Management:
GET /user/question/all - Get all questions (user-admin).
GET /admin/question/all - Get all questions (admin-admin).
POST /questions - Add a new question (admin-only).
DELETE /questions/ - Delete a question by body (admin-only).
Answering Quiz:
POST /user/answer/submit - Submit answers for a quiz.

## Contributions

-routes: Contains application routes.
-controllers: Contains logic for handling quiz data.
-models: Defines data structure (if using a database).

Feel free to fork this repository and submit pull requests. For major changes, please open an issue to discuss what you'd like to change.

## License

Expand Down
53 changes: 34 additions & 19 deletions TestReadme.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,23 @@
-use mongodb local- url
-create .env
-write secrets
-MONGO_ATLAS="mongodb://localhost:27017/testdb"
-MONGO_ATLAS= your mongo atlas url
-ENCRYPT_SECRET_KEY=
-JWT_SECRET_KEY=
-test locally in following format


### Test routes
- getting all question for user/admin

```use http://localhost:2500/user/question/all
http://localhost:2500/admin/question/all

use sample bearer token - eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NzMxYjg1ZmU0ZTZjOTkzZGU5MzU2NTMiLCJpYXQiOjE3MzEzMTE3MTF9.YqquIuSsDwhHCDid8cywL2qlnocSDdOOyMqgZi_g-i4
```
### syntax signup body -POST request

### use similar syntax signup body
##### Admin body
```
{
Expand Down Expand Up @@ -37,6 +49,17 @@
}
```

#### admin body -sign in
```
{
"username": "[email protected]",
"password": "SecurePassword123",
}
```

use token generated for further use

### sample question document

```
Expand All @@ -48,14 +71,14 @@
},
{
"question": "What is the capital of Israel?",
"answer": ["London", "Washington", "Sydney", "Tel Aviv"],
"correctAnswer": "Tel Aviv",
"question": "What is the capital of Israel?",
"answer": ["London", "Washington", "Sydney", "Tel Aviv"],
"correctAnswer": "Tel Aviv",
}
```
CRUD-
delete-admin/question/delete
delete- http://localhost:2500/admin/question/delete
pass in body as shown
{
" id":"id of question",
Expand All @@ -68,7 +91,7 @@ pass in body as shown

}

update-put request in body admin/question/update
update-put request in body http://localhost:2500/admin/question/update
{
"id":"question id",
"update":{
Expand All @@ -80,19 +103,11 @@ update-put request in body admin/question/update

}

sample question is post request -use beare token of admin as header
sample question is post request -use bearer token of admin as authorization


answers = [
{
questionId: mongoose.Types.ObjectId("questionId1"), // Replace with an actual questionId
selectedAnswer: "Paris"
},
{
questionId: mongoose.Types.ObjectId("questionId2"), // Replace with another questionId
selectedAnswer: "Madrid"
}
];

Sample token for testing purpose

user-token :eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NzMxYjg1ZmU0ZTZjOTkzZGU5MzU2NTMiLCJpYXQiOjE3MzEzMTE3MTF9.YqquIuSsDwhHCDid8cywL2qlnocSDdOOyMqgZi_g-i4

Expand All @@ -101,9 +116,9 @@ admin-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NzMwZDMxNTQwMz



answer submit -user/answer/submit -
answer submit -http://localhost:2500/user/answer/submit -

use suer token
use user token

{
"userId": "6731b85fe4e6c993de935653",
Expand Down
72 changes: 0 additions & 72 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"author": "manu p anand",
"license": "GPL-3.0",
"dependencies": {
"axios": "^1.7.7",
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"crypto-js": "^4.2.0",
Expand Down
2 changes: 1 addition & 1 deletion src/config/passwordValidate.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async function validateUserPassword(inputPassword,id,key){


}
async function validateAdminPassword(inputPassword,id){
async function validateAdminPassword(inputPassword,id,key){
try{const admin=await Admin.findOne(id)
const adminPassword=decrypt(admin.password,key)

Expand Down
13 changes: 10 additions & 3 deletions src/controllers/signinController.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ const adminSignIn=async (req,res)=>{
let userId,token
try{
//redis connection
await connectRedis();
const client =getClient()
// await connectRedis();
// const client =getClient()
try{ // Quiz User input validation
const validate=signInValidate(req.body)
if(!validate.success){
Expand All @@ -137,9 +137,16 @@ const adminSignIn=async (req,res)=>{
}

try{ // checking if Quiz user exists in database
const existingUser= await User.findOne({
const existingUser= await Admin.findOne({
username:req.body.username
})
console.log(existingUser)
if (!existingUser) {
logger.error("Admin user not found");
return res.status(404).json({
message: "Admin user not found",
});
}
userId=existingUser.username

if(existingUser){
Expand Down
3 changes: 1 addition & 2 deletions src/controllers/signupController.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// creating first database of user/admin /signup
const logger=require('../config/logger')
const inputValidate=require('../config/inputValidation')
const {inputvalidate,signInValidate}=require('../config/inputValidation')
const {User}=require('../model/user.models')
const {Admin}=require('../model/admin.models')
const inputvalidate = require('../config/inputValidation')
const {encrypt}=require('../config/crypt')
const {generateToken}=require('../config/jwt')
require('dotenv').config()
Expand Down
2 changes: 1 addition & 1 deletion src/routes/result.router.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const resulController=require('../controllers/resultController')
router.get('/result',resulController.resultUser)

//get result for all , admin only
router.get('/allresult',resulController.resultUser)
// router.get('/allresult',resulController.resultUser)


module.exports=router

0 comments on commit 1df5c76

Please sign in to comment.