WP Assignment 2
WP Assignment 2
1|Page
1) TASK 01: Backend (Node.js + Express.js)
• Create an Express server with the following endpoints:
o POST /api/signup:
▪ Accepts user data from the sign-up form.
▪ Hashes the password using bcrypt.
▪ Stores the user details in a MongoDB database.
▪ Returns a success message or an error if the email is already in use.
o POST /api/signin:
▪ Accepts user credentials from the sign-in form.
▪ Verifies the password using bcrypt.
▪ If successful, generates a JWT (JSON Web Token) and sends it back to the
client.
▪ If the credentials are invalid, returns an error message.
o GET /api/protected:
▪ A protected route that requires a valid JWT to access.
▪ Returns a message or user data to indicate successful access.
Answer:
Below is a Node.js application using Express.js, bcrypt, jsonwebtoken, and
mongoose to meet the requirements for this task:
1. Make sure to install the necessary dependencies:
npm install express mongoose bcrypt jsonwebtoken body-parser
Here is the code:
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
2|Page
const generateToken = (user) => {
return jwt.sign({ id: user._id }, 'your_secret_key', { expiresIn: '1h' });
};
3|Page
}
4|Page
bash
Copy code
npm install mongoose
MongoDB User Schema with Unique Indexing
Below is the code to define the User schema with the required fields:
Javascript
Code:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: { type: String, required: true }, // Username field
email: { type: String, required: true, unique: true }, // Email field with unique index
password: { type: String, required: true }, // Password field
});
userSchema.index({ email: 1 }, { unique: true });
const User = mongoose.model('User', userSchema);
module.exports = User;
Steps to Use
1. Database Connection: Connect to MongoDB using Mongoose. Here's an example:
javascript
Copy code
const mongoose = require('mongoose');
const mongoURI = 'mongodb://localhost:27017/authDB';
mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch((error) => console.error('Failed to connect to MongoDB:', error));
2. Integration with Signup Endpoint: Use the User model created above to store user
data during the signup process:
javascript
Copy code
const User = require('./models/User'); // Assuming the model file is named User.js
5|Page
res.status(400).json({ message: 'Email already in use!' });
} else {
res.status(500).json({ message: 'An error occurred!' });
}
}
});
Notes
1. Unique Indexing:
o MongoDB automatically creates a unique index on the email field due to {
unique: true } in the schema.
2. Validation:
o Ensure all fields are required using required: true in the schema definition.
3. Error Handling:
o The code checks for error.code === 11000 to detect duplicate email errors
during user creation.
6|Page