-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
554 lines (503 loc) · 16.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
const express = require('express')
const app = express()
require('dotenv').config()
const cors = require('cors')
const nodemailer = require('nodemailer')
const cookieParser = require('cookie-parser')
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb')
const jwt = require('jsonwebtoken')
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
const port = process.env.PORT || 8000
// const { Resend } = require('resend')
// const resend = new Resend(api_key)
// middleware
const corsOptions = {
origin: [
'http://localhost:5173',
'http://localhost:5174',
'https://user-email-password-auth-8dfb6.web.app',
],
credentials: true,
optionSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
}
app.use(cors(corsOptions))
app.options('', cors(corsOptions))
app.use(express.json())
app.use(cookieParser())
// send email
const sendEmail = (emailAddress, emailData) => {
const transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 587,
secure: false, // Use `true` for port 465, `false` for all other ports
auth: {
user: process.env.TRANSPORTER_EMAIL,
pass: process.env.TRANSPORTER_PASS,
},
})
// verify transporter
// verify connection configuration
transporter.verify(function (error, success) {
if (error) {
console.log(error)
} else {
console.log('Server is ready to take our messages')
}
})
const mailBody = {
from: `"Luca" <${process.env.TRANSPORTER_EMAIL}>`, // sender address
to: emailAddress, // list of receivers
subject: emailData.subject, // Subject line
html: emailData.message, // html body
}
transporter.sendMail(mailBody, (error, info) => {
if (error) {
console.log(error)
} else {
console.log('Email Sent: ' + info.response)
}
})
}
// Verify Token Middleware
const verifyToken = async (req, res, next) => {
const token = req.cookies?.token
console.log(token)
if (!token) {
return res.status(401).send({ message: 'unauthorized access' })
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.log(err)
return res.status(401).send({ message: 'unauthorized access' })
}
req.user = decoded
next()
})
}
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster7.fgw7s.mongodb.net/?retryWrites=true&w=majority&appName=Cluster7`
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
})
async function run() {
try {
const db = client.db('luca')
const roomsCollection = db.collection('rooms')
const usersCollection = db.collection('users')
const bookingsCollection = db.collection('bookings')
const packagesCollection = db.collection('packages')
const tourGuideCollection = db.collection('tour-guide')
const wishlistCollection = db.collection('wishlists')
// verify admin middleware
const verifyAdmin = async (req, res, next) => {
console.log('hello')
const user = req.user
const query = { email: user?.email }
const result = await usersCollection.findOne(query)
console.log(result?.role)
if (!result || result?.role !== 'admin')
return res.status(401).send({ message: 'unauthorized access!!' })
next()
}
// verify host middleware
const verifyHost = async (req, res, next) => {
console.log('hello')
const user = req.user
const query = { email: user?.email }
const result = await usersCollection.findOne(query)
console.log(result?.role)
if (!result || result?.role !== 'host') {
return res.status(401).send({ message: 'unauthorized access!!' })
}
next()
}
// auth related api
app.post('/jwt', async (req, res) => {
const user = req.body
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '365d',
})
res
.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'strict',
})
.send({ success: true })
})
// Logout
app.get('/logout', async (req, res) => {
try {
res
.clearCookie('token', {
maxAge: 0,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'strict',
})
.send({ success: true })
console.log('Logout successful')
} catch (err) {
res.status(500).send(err)
}
})
// create-payment-intent
app.post('/create-payment-intent', verifyToken, async (req, res) => {
const price = req.body.price
const priceInCent = parseFloat(price) * 100
if (!price || priceInCent < 1) return
// generate clientSecret
const { client_secret } = await stripe.paymentIntents.create({
amount: priceInCent,
currency: 'usd',
// In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default.
automatic_payment_methods: {
enabled: true,
},
})
// send client secret as response
res.send({ clientSecret: client_secret })
})
// save a user data in db
app.put('/user', async (req, res) => {
const user = req.body
const query = { email: user?.email }
// check if user already exists in db
const isExist = await usersCollection.findOne(query)
if (isExist) {
if (user.status === 'Requested') {
// if existing user try to change his role
const result = await usersCollection.updateOne(query, {
$set: { status: user?.status },
})
return res.send(result)
} else {
// if existing user login again
return res.send(isExist)
}
}
// save user for the first time
const options = { upsert: true }
const updateDoc = {
$set: {
...user,
timestamp: Date.now(),
},
}
const result = await usersCollection.updateOne(query, updateDoc, options)
// welcome new user
sendEmail(user?.email, {
subject: 'Welcome to Luca!',
message: `Hope you will find you destination`,
})
res.send(result)
})
// get a user info by email from db
app.get('/user/:email', async (req, res) => {
const email = req.params.email
const result = await usersCollection.findOne({ email })
res.send(result)
})
// get all users data from db
app.get('/users', verifyToken, verifyAdmin, async (req, res) => {
const result = await usersCollection.find().toArray()
res.send(result)
})
//update a user role
app.patch('/users/update/:email', async (req, res) => {
const email = req.params.email
const user = req.body
const query = { email }
const updateDoc = {
$set: { ...user, timestamp: Date.now() },
}
const result = await usersCollection.updateOne(query, updateDoc)
res.send(result)
})
// Get all rooms from db
app.get('/rooms', async (req, res) => {
const category = req.query.category
console.log(category)
let query = {}
if (category && category !== 'null') query = { category }
const result = await roomsCollection.find(query).toArray()
res.send(result)
})
// Save a room data in db
app.post('/room', verifyToken, verifyHost, async (req, res) => {
const roomData = req.body
const result = await roomsCollection.insertOne(roomData)
res.send(result)
})
// get all rooms for host
app.get(
'/my-listings/:email',
verifyToken,
verifyHost,
async (req, res) => {
const email = req.params.email
let query = { 'host.email': email }
const result = await roomsCollection.find(query).toArray()
res.send(result)
}
)
// delete a room
app.delete('/room/:id', verifyToken, verifyHost, async (req, res) => {
const id = req.params.id
const query = { _id: new ObjectId(id) }
const result = await roomsCollection.deleteOne(query)
res.send(result)
})
// Get a single room data from db using _id
app.get('/room/:id', async (req, res) => {
const id = req.params.id
const query = { _id: new ObjectId(id) }
const result = await roomsCollection.findOne(query)
res.send(result)
})
// Get all packages
app.get('/packages', async (req, res) => {
const query = {}
const result = await packagesCollection.find(query).toArray()
res.send(result)
})
// Get a package details form db using _id
app.get('/package/details/:id', async (req, res) => {
const id = req.params.id
const query = { _id: new ObjectId(id) }
const result = await packagesCollection.findOne(query)
res.send(result)
})
// Save a booking data in db
app.post('/booking', verifyToken, async (req, res) => {
const bookingData = req.body
// save room booking info
const result = await bookingsCollection.insertOne(bookingData)
// send email to guest
sendEmail(bookingData?.guest?.email, {
subject: 'Booking Successful!',
message: `You've successfully booked a room through Luca. Transaction Id: ${bookingData.transactionId}`,
})
// send email to host
sendEmail(bookingData?.host?.email, {
subject: 'Your room got booked!',
message: `Get ready to welcome ${bookingData.guest.name}.`,
})
res.send(result)
})
// update room data
app.put('/room/update/:id', verifyToken, verifyHost, async (req, res) => {
const id = req.params.id
const roomData = req.body
const query = { _id: new ObjectId(id) }
const updateDoc = {
$set: roomData,
}
const result = await roomsCollection.updateOne(query, updateDoc)
res.send(result)
})
// update Room Status
app.patch('/room/status/:id', async (req, res) => {
const id = req.params.id
const status = req.body.status
// change room availability status
const query = { _id: new ObjectId(id) }
const updateDoc = {
$set: { booked: status },
}
const result = await roomsCollection.updateOne(query, updateDoc)
res.send(result)
})
// get all booking for a guest
app.get('/my-bookings/:email', verifyToken, async (req, res) => {
const email = req.params.email
const query = { 'guest.email': email }
const result = await bookingsCollection.find(query).toArray()
res.send(result)
})
// get all booking for a host
app.get(
'/manage-bookings/:email',
verifyToken,
verifyHost,
async (req, res) => {
const email = req.params.email
const query = { 'host.email': email }
const result = await bookingsCollection.find(query).toArray()
res.send(result)
}
)
// delete a booking
app.delete('/booking/:id', verifyToken, async (req, res) => {
const id = req.params.id
const query = { _id: new ObjectId(id) }
const result = await bookingsCollection.deleteOne(query)
res.send(result)
})
// Admin Statistics
app.get('/admin-stat', verifyToken, verifyAdmin, async (req, res) => {
const bookingDetails = await bookingsCollection
.find(
{},
{
projection: {
date: 1,
price: 1,
},
}
)
.toArray()
const totalUsers = await usersCollection.countDocuments()
const totalRooms = await roomsCollection.countDocuments()
const totalPrice = bookingDetails.reduce(
(sum, booking) => sum + booking.price,
0
)
// const data = [
// ['Day', 'Sales'],
// ['9/5', 1000],
// ['10/2', 1170],
// ['11/1', 660],
// ['12/11', 1030],
// ]
const chartData = bookingDetails.map((booking) => {
const day = new Date(booking.date).getDate()
const month = new Date(booking.date).getMonth() + 1
const data = [`${day}/${month}`, booking?.price]
return data
})
chartData.unshift(['Day', 'Sales'])
// chartData.splice(0, 0, ['Day', 'Sales'])
console.log(chartData)
console.log(bookingDetails)
res.send({
totalUsers,
totalRooms,
totalBookings: bookingDetails.length,
totalPrice,
chartData,
})
})
// Host Statistics
app.get('/host-stat', verifyToken, verifyHost, async (req, res) => {
const { email } = req.user
const bookingDetails = await bookingsCollection
.find(
{ 'host.email': email },
{
projection: {
date: 1,
price: 1,
},
}
)
.toArray()
const totalRooms = await roomsCollection.countDocuments({
'host.email': email,
})
const totalPrice = bookingDetails.reduce(
(sum, booking) => sum + booking.price,
0
)
const { timestamp } = await usersCollection.findOne(
{ email },
{ projection: { timestamp: 1 } }
)
const chartData = bookingDetails.map((booking) => {
const day = new Date(booking.date).getDate()
const month = new Date(booking.date).getMonth() + 1
const data = [`${day}/${month}`, booking?.price]
return data
})
chartData.unshift(['Day', 'Sales'])
// chartData.splice(0, 0, ['Day', 'Sales'])
console.log(chartData)
console.log(bookingDetails)
res.send({
totalRooms,
totalBookings: bookingDetails.length,
totalPrice,
chartData,
hostSince: timestamp,
})
})
// Guest Statistics
app.get('/guest-stat', verifyToken, async (req, res) => {
const { email } = req.user
const bookingDetails = await bookingsCollection
.find(
{ 'guest.email': email },
{
projection: {
date: 1,
price: 1,
},
}
)
.toArray()
const totalPrice = bookingDetails.reduce(
(sum, booking) => sum + booking.price,
0
)
const { timestamp } = await usersCollection.findOne(
{ email },
{ projection: { timestamp: 1 } }
)
const chartData = bookingDetails.map((booking) => {
const day = new Date(booking.date).getDate()
const month = new Date(booking.date).getMonth() + 1
const data = [`${day}/${month}`, booking?.price]
return data
})
chartData.unshift(['Day', 'Sales'])
// chartData.splice(0, 0, ['Day', 'Sales'])
console.log(chartData)
console.log(bookingDetails)
res.send({
totalBookings: bookingDetails.length,
totalPrice,
chartData,
guestSince: timestamp,
})
})
// Tour guide section
// 1. Get all the tour guide
app.get('/all-tour-guide', async (req, res) => {
const query = {}
const result = await tourGuideCollection.find(query).toArray()
res.send(result)
})
// 2. Get single guide info by id
app.get('/tourGuideDetails/:id', async (req, res) => {
const id = req.params.id
const query = { _id: new ObjectId(id) }
const result = await tourGuideCollection.findOne(query)
res.send(result)
})
// 3. register as a tour guide
// Packages dealing section
app.post('/addToWishlist', async (req, res) => {
const data = req.body
const result = await wishlistCollection.insertOne(data)
res.send(result)
})
// Send a ping to confirm a successful connection
await client.db('admin').command({ ping: 1 })
console.log(
'Pinged your deployment. You successfully connected to MongoDB!'
)
} finally {
// Ensures that the client will close when you finish/error
}
}
run().catch(console.dir)
app.get('/', (req, res) => {
res.send('Hello from Luca Server..')
})
app.listen(port, () => {
console.log(`Luca server is running on port ${port}`)
})