Skip to content

Commit

Permalink
Merge pull request #117 from sujal-98/sujal
Browse files Browse the repository at this point in the history
ECOM API
  • Loading branch information
dishamodi0910 authored May 20, 2024
2 parents 6e44dff + f56e525 commit 7067b6f
Show file tree
Hide file tree
Showing 14 changed files with 775 additions and 0 deletions.
8 changes: 8 additions & 0 deletions New_APIs/Ecom/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Ignore node_modules directory
node_modules/

# Ignore .env files
.env


package-lock.json
175 changes: 175 additions & 0 deletions New_APIs/Ecom/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# **Ecom API**

### Overview
This project is an Express.js based API for managing users, authentication, products, carts, and orders. It provides endpoints for CRUD operations on these resources and includes authentication and authorization middleware.

### Prerequisites
Before you begin, ensure you have met the following requirements:

Node.js installed
MongoDB installed and running
npm installed

### Installation

**Clone the repository:**
git clone https://github.com/your-username/repository-name.git
cd repository-name

**Install dependencies:**
npm install


### Create a .env file in the root directory and add your environment variables:
PORT=Your_Desired_Port
MONGO_URL=your_mongodb_connection_string
JWT_SECRET=your_jwt_secret
SECRET_PHRASE=your_secret_phrase

### API ENDPOINTS

**Authentication**
- Register
Endpoint: /api/auth/register
Method: POST
Description: Register a new user.
Body:
{
"username": "exampleuser",
"email": "[email protected]",
"password": "password"
}

- Login
Endpoint: /api/auth/login
Method: POST
Description: Login a user.
Body:
{
"username": "exampleuser",
"password": "password"
}

**User Management**

- Update User
Endpoint: /api/user/:id
Method: PUT
Description: Update a user's information.
Authorization: Requires token verification.

- Delete User
Endpoint: /api/user/:id
Method: DELETE
Description: Delete a user.
Authorization: Requires token verification.

- Get User
Endpoint: /api/user/find/:id
Method: GET
Description: Get a user's information.
Authorization: Requires admin verification.

- Get All Users
Endpoint: /api/user
Method: GET
Description: Get all users.
Authorization: Requires admin verification.

**Product Management**

- Add Product
Endpoint: /api/prod/add
Method: POST
Description: Add a new product.
Authorization: Requires admin verification.

- Update Product
Endpoint: /api/prod/upd/:id
Method: PUT
Description: Update a product.
Authorization: Requires admin verification.

- Delete Product
Endpoint: /api/prod/del/:id
Method: DELETE
Description: Delete a product.
Authorization: Requires admin verification.

- Get Product
Endpoint: /api/prod/find/:id
Method: GET
Description: Get a product by ID.

- Get All Products
Endpoint: /api/prod
Method: GET
Description: Get all products, with optional filtering by new or category.

**Cart Management**

- Add to Cart
Endpoint: /api/car/add
Method: POST
Description: Add a new item to the cart.
Authorization: Requires token verification.

- Update Cart
Endpoint: /api/car/upd/:id
Method: PUT
Description: Update a cart item.
Authorization: Requires token verification.

- Delete Cart Item
Endpoint: /api/car/del/:id
Method: DELETE
Description: Delete a cart item.
Authorization: Requires token verification.

- Get Cart
Endpoint: /api/car/find/:id
Method: GET
Description: Get cart items for a user.

- Get All Carts
Endpoint: /api/car
Method: GET
Description: Get all cart items.
Authorization: Requires admin verification.

**Order Management**

- Add Order
Endpoint: /api/ord/add
Method: POST
Description: Add a new order.
Authorization: Requires token verification.

- Update Order
Endpoint: /api/ord/upd/:id
Method: PUT
Description: Update an order.
Authorization: Requires admin verification.

- Delete Order
Endpoint: /api/ord/del/:id
Method: DELETE
Description: Delete an order.
Authorization: Requires admin verification.

- Get Order
Endpoint: /api/ord/find/:id
Method: GET
Description: Get an order by user ID.

- Get All Orders
Endpoint: /api/ord
Method: GET
Description: Get all orders.
Authorization: Requires admin verification.

- Get Monthly Income
Endpoint: /api/ord/income
Method: GET
Description: Get monthly income.
Authorization: Requires admin verification.
35 changes: 35 additions & 0 deletions New_APIs/Ecom/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const express=require('express');
const app=express();
const dotenv=require('dotenv')
dotenv.config();
const mongoose=require('mongoose')
const userRoute=require('./routes/user')
const authRoute=require('./routes/auth')
const prodRoute=require('./routes/prod')
const carRoute=require('./routes/car')
const orderRoute=require('./routes/ord')



mongoose.connect(process.env.url
).then(()=>{
console.log("Db connection successfull"
)
}).catch((err)=>{
console.log(err);
})


//middlewares

app.use(express.json())
app.use("/api/auth",authRoute)
app.use("/api/user",userRoute)
app.use("/api/prod",prodRoute)
app.use("/api/car",carRoute)
app.use("/api/ord",orderRoute)


app.listen(process.env.Port,()=>{
console.log("server running");
})
14 changes: 14 additions & 0 deletions New_APIs/Ecom/models/cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose=require('mongoose')

const CartSchema=new mongoose.Schema({
userId:{type:String,required:true},
products:[{
product:{type:String,required:true},
quantity:{
type:Number,
default:1
}
}]
},{timestamps:true});

module.exports=mongoose.model('Cart',CartSchema)
17 changes: 17 additions & 0 deletions New_APIs/Ecom/models/order.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const mongoose=require('mongoose')

const OrderSchema=new mongoose.Schema({
userId:{type:String,required:true},
products:[{
product:{type:String,required:true},
quantity:{
type:Number,
default:1
}
}],
amount:{type:Number,required:true},
address:{type:Object,required:true},
status:{type:String, default:"pending"}
},{timeStamps:true});

module.exports=mongoose.model('order',OrderSchema)
14 changes: 14 additions & 0 deletions New_APIs/Ecom/models/product.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose=require('mongoose')

const ProductSchema=new mongoose.Schema({
title:{type:String,required:true,unique:true},
description:{type:String,required:true,unique:true},
img:{type:String,required:true,unique:true},
categories:{type:Array},
size:{type:String},
color:{type:String},
price:{type:String,required:true,unique:true},

},{timestamps:true});

module.exports=mongoose.model('Product',ProductSchema)
13 changes: 13 additions & 0 deletions New_APIs/Ecom/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const mongoose=require('mongoose')

const UserSchema=new mongoose.Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
password:{type:String,required:true,unique:true},
isAdmin:{
type:Boolean,
default: false
},
},{timestamps:true});

module.exports=mongoose.model('User',UserSchema)
21 changes: 21 additions & 0 deletions New_APIs/Ecom/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "ecom",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"crypto-js": "^4.2.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.3.1",
"stripe": "^15.0.0"
}
}
54 changes: 54 additions & 0 deletions New_APIs/Ecom/routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const router=require('express').Router();
const User=require('../models/user')
const crypto=require("crypto-js")
const jwt=require('jsonwebtoken')

router.post("/register",async(req,res)=>{
const newuser=new User({
username:req.body.username,
email:req.body.email,
password:crypto.AES.encrypt(req.body.password,process.env.secretphrase).toString()
});
try{
const saved=await newuser.save();
res.status(201).json(saved)}
catch(err){
res.status(500).json(err);
}
})

//login route
router.post("/login", async (req, res, next) => {
try {
const user = await User.findOne({ username: req.body.username });

if (!user) {
return res.status(401).json("Wrong credentials1");
}

const hash = crypto.AES.decrypt(user.password, process.env.secretphrase);
let originalpass = hash.toString(crypto.enc.Utf8);

if (originalpass !== req.body.password) {
return res.status(401).json("Wrong credentials2");
}

const access=jwt.sign({
id:user._id,
isAdmin:user.isAdmin,
},
process.env.jwtsecret,
{expiresIn:'3d'}
)
console.log(user._doc)
const { password, ...others } = user._doc;

res.status(200).json({...others,access});
} catch (err) {
res.status(500).json(err);
}
});



module.exports=router;
Loading

0 comments on commit 7067b6f

Please sign in to comment.