-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
346 lines (304 loc) · 12.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config();
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const port = process.env.PORT || 5000;
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Mongodb
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.7t8vw3l.mongodb.net/?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
// middleware for verify JWT
function verifyJWT(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send('Unauthorized Access');
}
const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, function (err, decoded) {
if (err) {
return res.status(403).send({ message: "Forbidden access" })
}
req.decoded = decoded
next();
})
};
async function run() {
try {
const userCollection = client.db('usedLaptopShop').collection('users');
const productCollection = client.db('usedLaptopShop').collection('products');
const bookingCollection = client.db('usedLaptopShop').collection('bookings');
const blogCollection = client.db('usedLaptopShop').collection('blogContents')
const paymentCollection = client.db('usedLaptopShop').collection('payments');
// JWT
app.get('/jwt', async (req, res) => {
const email = req.query.email;
const query = { email: email };
const user = await userCollection.findOne(query);
if (user) {
const token = jwt.sign({ email }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "10h" });
return res.send({ accessToken: token })
}
res.status(403).send({ accessToken: '' });
});
// saving users information in the db
app.post('/allUsers', async (req, res) => {
const user = req.body;
const query = {
name: user.name,
email: user.email
}
const alreadyCreatedUsers = await userCollection.find(query).toArray();
if (alreadyCreatedUsers.length) {
res.send(alreadyCreatedUsers);
return;
}
const result = await userCollection.insertOne(user);
res.send(result);
});
// Getting the saved user information form db
app.get('/allUsers', verifyJWT, async (req, res) => {
const query = {};
const cursor = userCollection.find(query);
const users = await cursor.toArray();
res.send(users);
});
// Getting verified users
app.get('/verifiedUsers', async (req, res) => {
const email = req.query.email;
const query = { email: email };
const result = await userCollection.findOne(query);
res.send(result);
})
// Getting user role
app.get('/allUsersRole', verifyJWT, async (req, res) => {
const email = req.query.email;
const query = { email: email };
const cursor = userCollection.find(query);
const user = await cursor.toArray();
res.send(user);
});
// API for Changing the user role to admin
app.patch('/allUsers', async (req, res) => {
const email = req.query.email;
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: {
role: "Admin"
}
};
const result = await userCollection.updateOne(filter, updateDoc, options);
res.send(result);
});
// API for making the seller verified and store in db
app.patch('/verifySeller', async (req, res) => {
const email = req.query.email;
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: {
verified: true
}
};
const result = await userCollection.updateOne(filter, updateDoc, options);
res.send(result);
});
// Getting all the buyers
app.get('/allBuyers', verifyJWT, async (req, res) => {
const role = req.query.role;
const query = { role: role };
const buyers = await userCollection.find(query).toArray();
res.send(buyers);
});
// Getting all the sellers
app.get('/allSellers', verifyJWT, async (req, res) => {
const role = req.query.role;
const query = { role: role };
const sellers = await userCollection.find(query).toArray();
res.send(sellers);
});
// Deleting user from the db
app.delete('/allUsers/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await userCollection.deleteOne(query);
res.send(result);
});
// Saving product information in the db
app.post('/product', async (req, res) => {
const product = req.body;
const result = await productCollection.insertOne(product);
res.send(result);
});
// Getting all the products from db without booked products
app.get('/products', async (req, res) => {
const query = {};
const cursor = productCollection.find(query);
const allProducts = await cursor.toArray();
const products = allProducts.filter(product => !product.booked);
res.send(products);
});
// Getting a specific product for edit
app.get('/products/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const product = await productCollection.findOne(query);
res.send(product);
});
// Editing product information
app.patch('/products/:id', async (req, res) => {
const id = req.params.id;
const updatedInfo = req.body;
const filter = { _id: new ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
productName: updatedInfo.productName,
originalPrice: updatedInfo.originalPrice,
resalePrice: updatedInfo.resalePrice,
yearOfPurchase: updatedInfo.yearOfPurchase,
category: updatedInfo.category,
condition: updatedInfo.condition,
location: updatedInfo.location,
phoneNumber: updatedInfo.phoneNumber,
productDescription: updatedInfo.productDescription
}
};
const result = await productCollection.updateOne(filter, updateDoc, options);
res.send(result);
});
// Getting user specific products from db
app.get('/userProducts', verifyJWT, async (req, res) => {
const email = req.query.email;
const decodedEmail = req.decoded.email;
if (email !== decodedEmail) {
res.status(403).send({ message: "forbidden access" })
}
const query = { email: email };
const cursor = productCollection.find(query);
const userProducts = await cursor.toArray();
res.send(userProducts);
});
// Deleting a product from db
app.delete('/products/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await productCollection.deleteOne(query);
res.send(result);
});
// saving users booking information in the db
app.post('/booking', async (req, res) => {
const booking = req.body;
const result = await bookingCollection.insertOne(booking);
res.send(result);
});
// Getting user specific bookings
app.get('/booking', verifyJWT, async (req, res) => {
const email = req.query.email;
const decodedEmail = req.decoded.email;
if (email !== decodedEmail) {
res.status(403).send({ message: "forbidden access" })
}
const query = { buyerEmail: email };
const result = await bookingCollection.find(query).toArray();
res.send(result);
});
// Showing the buyer information in the seller dashboard
app.get('/buyerInfo', verifyJWT, async (req, res) => {
const email = req.query.email;
const decodedEmail = req.decoded.email;
if (email !== decodedEmail) {
res.status(403).send({ message: "forbidden access" })
}
const query = { sellerEmail: email };
const result = await bookingCollection.find(query).toArray();
res.send(result);
});
// Getting product for payment
app.get('/booking/:id', async (req, res) => {
const id = req.params.id;
const query = { productId: id };
const result = await bookingCollection.findOne(query);
res.send(result);
})
// updating/marking booked product as booked=true
app.put('/booking/:id', async (req, res) => {
const productId = req.params.id;
const product = req.body;
const filter = { _id: new ObjectId(productId) };
const options = { upsert: true };
const updateDoc = {
$set: product
}
const result = await productCollection.updateOne(filter, updateDoc, options);
res.send(result);
});
// Blog contents
app.get('/blogContents', async (req, res) => {
const query = {};
const cursor = blogCollection.find(query);
const blogs = await cursor.toArray();
res.send(blogs);
});
app.post('/blogContents', async (req, res) => {
const query = req.body;
const result = await blogCollection.insertOne(query);
res.send(result);
});
app.delete('/blogContents/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await blogCollection.deleteOne(query);
res.send(result);
});
// Stripe payment api
app.post('/create-payment-intent', async (req, res) => {
const booking = req.body;
const price = booking.productPrice;
const amount = price * 100;
const paymentIntent = await stripe.paymentIntents.create({
currency: 'usd',
amount: amount,
"payment_method_types": [
"card"
]
});
res.send({
clientSecret: paymentIntent.client_secret,
});
});
// Saving payment information in the database
app.post('/payments', async (req, res) => {
const payment = req.body;
const result = await paymentCollection.insertOne(payment);
const productId = payment.productId;
const filter = { productId: productId }
const updateDoc = {
$set: {
paid: true,
transactionId: payment.transactionId
}
}
const updateResult = await bookingCollection.updateOne(filter, updateDoc);
res.send(result);
});
}
finally {
}
}
run().catch(console.dir);
app.get('/', async (req, res) => {
res.send("server is running");
});
app.listen(port, () => console.log(`used laptop server is running on port ${port}`));