Skip to content

Commit d32fbcf

Browse files
committed
Adding Project
1 parent 831eff0 commit d32fbcf

38 files changed

+4569
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules
2+
.env

.vscode/settings.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"liveServer.settings.port": 5501
3+
}

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,33 @@
1+
Website Link: <a href="https://pratham-d14.github.io/E-Commerce/">E-Commerce</a><br> <br>
2+
<b>Description </b><br>
3+
This project is an E-commerce website developed using HTML, CSS, JavaScript, Node.js, and MongoDB. It allows users to register, browse products, add them to their cart, and make purchases. The system has two types of users: regular users and administrators.
4+
5+
<b>User Roles</b>
6+
1. User: Browse products, add products to cart, make purchases.
7+
2. Admin: Manage product database, including adding, removing, or updating products.
8+
9+
10+
11+
<b>Installation</b><br>
12+
To run this project locally, follow these steps:
13+
1. Clone the repository: git clone https://github.com/Pratham-D14/E-Commerce.git
14+
2. Navigate to the project directory: E-Commerce
15+
3. Install dependencies: npm/yarn install
16+
4. Set up the MongoDB database and create a .env file in the root directory with the following environment variables: DB_CONNECTION=your_mongodb_connection_stringJWT_SECRET=your_jwt_secret_key
17+
18+
19+
<b>Usage</b>
20+
1. Start the server: npm start
21+
22+
<b>Technologies Used</b>
23+
1. HTML, CSS, and JavaScript are used in Frontend Development
24+
2. Node.js is used for Backend and Creating API's
25+
3. MongoDB used to store users and product data in Database
26+
4. JSON Web Token (JWT): Used for authentication and generating access tokens for user sessions.
27+
28+
<b>Access to Website</b> <br>
29+
1. Users Panel: Simply register and login with username and passsword
30+
2. If you wish to access the admin panel, please contact me via GitHub or email to obtain the credentials. <br>
31+
i. GitHub: Pratham-D14 <br>
32+
ii. Email: [email protected]
133
# E-Commerce

backend/backup.js

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
const mongoose = require("mongoose");
2+
const express = require("express");
3+
4+
const userDbConnection = require("./config/userdbConnection");
5+
const userSchema = require("./models/userSchema");
6+
7+
const jwt = require("jsonwebtoken");
8+
const crypto = require("crypto");
9+
10+
const cors = require("cors");
11+
const { access } = require("fs");
12+
let app = express();
13+
14+
app.use(express.json());
15+
app.use(cors());
16+
17+
userDbConnection();
18+
19+
// Empty Array to storage Refresh Token
20+
let refreshTokens = [];
21+
let loggedInUser;
22+
23+
// Posts
24+
let posts = [
25+
{
26+
id: 1,
27+
title: "Post 1",
28+
content: "Content of Post 1",
29+
},
30+
{ id: 2, title: "Post 2", content: "Content of Post 2" },
31+
{
32+
id: 3,
33+
title: "Post 3",
34+
content: "Content of Post 3",
35+
},
36+
];
37+
38+
// Generate access token secret
39+
const ACCESS_TOKEN_SECRET = crypto.randomBytes(64).toString("hex");
40+
41+
// Generate refresh token secret
42+
const REFRESH_TOKEN_SECRET = crypto.randomBytes(64).toString("hex");
43+
44+
// Registration Functionality
45+
app.post("/register", async (req, res) => {
46+
const { name, email, phone, username, password } = req.body;
47+
try {
48+
const register = new userSchema({ name, email, phone, username, password });
49+
await register.save();
50+
let id = register["_id"];
51+
res.status(200).send(`User added at id: ${id}`);
52+
} catch (error) {
53+
if (error.errors.message == "Email is already registered") {
54+
return res.status(409).send("Email is already registered");
55+
}
56+
57+
if (error.errors.username.message == "Username is already taken") {
58+
return res.status(409).send("Username is already taken");
59+
}
60+
61+
res.status(400).send(error);
62+
}
63+
});
64+
65+
// Login Functionality
66+
app.post("/login", async (req, res) => {
67+
const { username, password } = req.body;
68+
try {
69+
const user = await userSchema.findOne({ username, password });
70+
if (user) {
71+
// Generating Access Token
72+
let accessToken = jwt.sign({ username: username }, ACCESS_TOKEN_SECRET, {
73+
expiresIn: "25s",
74+
});
75+
76+
// Generating Refresh Token
77+
let refreshToken = jwt.sign(
78+
{ username: username, password: password },
79+
REFRESH_TOKEN_SECRET
80+
);
81+
loggedInUser = username;
82+
refreshTokens.push(refreshToken);
83+
84+
const tokens = await userSchema.findOneAndUpdate(
85+
{ username: username },
86+
{ $set: { accessToken: accessToken, refreshToken: refreshToken } },
87+
{ new: true }
88+
);
89+
90+
res.status(200).json({
91+
username,
92+
password,
93+
accessToken,
94+
refreshToken,
95+
});
96+
} else {
97+
res.status(404).send("Invalid Username or Password");
98+
}
99+
} catch (error) {
100+
console.error(error);
101+
res.status(500).send(error);
102+
}
103+
});
104+
105+
async function Authenticate(req, res, next) {
106+
// const username = req.body.username;
107+
let dbAccessToken = await userSchema.find();
108+
109+
let accessToken;
110+
dbAccessToken.forEach((e) => {
111+
if (e.username == loggedInUser) {
112+
accessToken = e.accessToken;
113+
}
114+
});
115+
jwt.verify(accessToken, ACCESS_TOKEN_SECRET, (err, user) => {
116+
if (err) return res.sendStatus(403);
117+
118+
req.user = user;
119+
next();
120+
});
121+
}
122+
123+
// Accessing Post with Valid accessToken
124+
app.get("/posts", Authenticate, (req, res) => {
125+
res.json(posts);
126+
console.log(posts);
127+
});
128+
129+
app.get("/refresh", async (req, res) => {
130+
const username = req.body.username;
131+
let dbRefreshToken = await userSchema.find();
132+
let refreshToken;
133+
let accessToken;
134+
135+
dbRefreshToken.forEach(async (e) => {
136+
if (e.username == username) {
137+
refreshToken = e.refreshToken;
138+
jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, (err, user) => {
139+
if (err) {
140+
return res.status(403).send(err); // Forbidden
141+
}
142+
143+
accessToken = jwt.sign(
144+
{ username: user.username, password: user.password },
145+
ACCESS_TOKEN_SECRET,
146+
{
147+
expiresIn: "25s",
148+
}
149+
);
150+
res.json({ accessToken });
151+
});
152+
153+
const tokens = await userSchema.findOneAndUpdate(
154+
{ username: e.username },
155+
{ $set: { accessToken: accessToken } },
156+
{ new: true }
157+
);
158+
}
159+
});
160+
});
161+
162+
app.listen(8000);

backend/config/userdbConnection.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const mongoose = require("mongoose");
2+
require("dotenv").config();
3+
4+
const userDbConnection = async () => {
5+
try {
6+
await mongoose.connect(process.env.userDB_URL);
7+
console.log("Database connected successfully");
8+
} catch (error) {
9+
console.log(error);
10+
process.exit(1);
11+
}
12+
};
13+
14+
module.exports = userDbConnection;
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
const Product = require("../models/productSchema");
2+
0;
3+
const productSchema = require("../models/productSchema");
4+
5+
exports.createProduct = async (req, res) => {
6+
try {
7+
const { name, description, price, type, imageUrl } = req.body;
8+
const product = new Product({ name, description, price, type, imageUrl });
9+
await product.save();
10+
res.status(201).json(product);
11+
} catch (error) {
12+
res.status(400).json({ message: error.message });
13+
}
14+
};
15+
16+
exports.getData = async (req, res) => {
17+
const data = await productSchema.find();
18+
res.status(200).send(data);
19+
};
20+
21+
exports.deleteProduct = async (req, res) => {
22+
try {
23+
const { productId } = req.body;
24+
// console.log(productId);
25+
26+
await productSchema.findByIdAndDelete(productId);
27+
res.status(200).json("Deleted Successfully");
28+
} catch (error) {
29+
console.log(error);
30+
}
31+
};
32+
33+
exports.editProduct = async (req, res) => {
34+
try {
35+
const { id, name, description, price, type } = req.body;
36+
37+
await productSchema.findByIdAndUpdate(
38+
id,
39+
{
40+
$set: {
41+
name: name,
42+
description: description,
43+
price: price,
44+
type: type,
45+
},
46+
},
47+
{ new: true }
48+
);
49+
res.status(200).json("Data Updated Suceesfully");
50+
} catch (error) {
51+
console.log(error);
52+
}
53+
};

0 commit comments

Comments
 (0)