0% found this document useful (0 votes)
17 views6 pages

WP Assignment 2

The document outlines an assignment for a Web Programming course, detailing the creation of a Node.js application with Express.js for user authentication. It includes endpoints for user signup, signin, and a protected route, utilizing MongoDB for data storage and bcrypt for password hashing. Additionally, it provides instructions for setting up a MongoDB database with unique indexing on the email field to prevent duplicate accounts.

Uploaded by

unafees2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views6 pages

WP Assignment 2

The document outlines an assignment for a Web Programming course, detailing the creation of a Node.js application with Express.js for user authentication. It includes endpoints for user signup, signin, and a protected route, utilizing MongoDB for data storage and bcrypt for password hashing. Additionally, it provides instructions for setting up a MongoDB database with unique indexing on the email field to prevent duplicate accounts.

Uploaded by

unafees2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

University of Engineering and Technology Peshawar

Department of Computer Science and Information


Technology
Name: Nafees Ahmad
Reg. No: 23PWBCS1040
Sir: Mohammad
Assignment: 2
Course: Web Programming
Date of Submission: 09-January-2025

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');

const app = express();


app.use(bodyParser.json());

const mongoURI = 'mongodb://localhost:27017/authDB';


mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const userSchema = new mongoose.Schema({


email: { type: String, unique: true, required: true },
password: { type: String, required: true },
});

const User = mongoose.model('User', userSchema);

2|Page
const generateToken = (user) => {
return jwt.sign({ id: user._id }, 'your_secret_key', { expiresIn: '1h' });
};

app.post('/api/signup', async (req, res) => {


const { email, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ email, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: 'User registered successfully!' });
} catch (error) {
if (error.code === 11000) {
res.status(400).json({ message: 'Email already in use!' });
} else {
res.status(500).json({ message: 'An error occurred!' });
}
}
});

app.post('/api/signin', async (req, res) => {


const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ message: 'Invalid credentials!' });
}

const isPasswordValid = await bcrypt.compare(password, user.password);


if (!isPasswordValid) {
return res.status(400).json({ message: 'Invalid credentials!' });
}

const token = generateToken(user);


res.status(200).json({ message: 'Login successful!', token });
} catch (error) {
res.status(500).json({ message: 'An error occurred!' });
}
});

const authenticateToken = (req, res, next) => {


const token = req.headers['authorization'];
if (!token) {
return res.status(403).json({ message: 'Access denied!' });

3|Page
}

jwt.verify(token, 'your_secret_key', (err, user) => {


if (err) {
return res.status(403).json({ message: 'Invalid token!' });
}
req.user = user;
next();
});
};

app.get('/api/protected', authenticateToken, (req, res) => {


res.status(200).json({ message: 'Access granted to protected route!' });
});

const PORT = 3000;


app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Key Notes:
1. Dependencies:
 bcrypt: For hashing passwords securely.
 jsonwebtoken: To create and verify JSON Web Tokens.
 mongoose: For MongoDB database interaction.
 body-parser: For parsing request bodies.
2. JWT Secret Key: Replace 'your_secret_key' with a secure and secret key in
production.
3. MongoDB Connection: Update the connection string to match your MongoDB
configuration.
4. Endpoints:
 POST /api/signup: Registers a new user.
 POST /api/signin: Authenticates the user and returns a JWT.
 GET /api/protected: Requires a valid JWT to access.

2) TASK 02: Database (MongoDB)


• Set up a MongoDB database to store user details:
o User model/schema should include fields for username, email, and password.
• Ensure unique indexing on the email field to prevent duplicate accounts.
Answer:
Prerequisites
1. Install MongoDB: Make sure MongoDB is installed and running locally or in a cloud
environment.
2. Install Dependencies: Ensure you have installed mongoose in your Node.js project
using:

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

app.post('/api/signup', async (req, res) => {


const { username, email, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ username, email, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: 'User registered successfully!' });
} catch (error) {
if (error.code === 11000) {

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

You might also like