-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
235 lines (204 loc) · 7.49 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
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
// Middleware
app.use(cors({
origin: [
// 'http://localhost:5173',
'https://car-doctor-client-99145.web.app',
'https://car-doctor-client-99145.firebaseapp.com',
'https://car-doctor-client-nion.netlify.app',
'https://hungry-pancake.surge.sh'
],
credentials: true
}));
// app.use(cors())
app.use(express.json());
app.use(cookieParser());
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.qf8hqc8.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0`;
console.log(uri);
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
/* User defined middlewares
const logger = async (req, res, next) => {
console.log('called:', req.host, req.originalUrl);
next();
}
const verifyToken = async (req, res, next) => {
const token = req.cookies.token;
console.log('Value of token in middleware:', token);
if (!token) {
return res.status(401).send({ message: 'unauthorized' });
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.log(err);
return res.status(401).send({ message: 'unauthorized' });
}
console.log('value in the token', decoded);
req.user = decoded;
next();
})
} */
// Custom Middlewares
const logger = (req, res, next) => {
console.log('Logging info:', req.method, req.url);
next();
}
const verifyToken = (req, res, next) => {
const token = req.cookies.token;
console.log('Token in the custom middleware', token);
if (!token) {
return res.status(401).send({ message: 'unauthorized access' });
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "unauthorized access" });
}
req.user = decoded;
next();
})
}
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
// await client.connect();
const database = client.db("carDoctorDB");
// const serviceCollection = database.collection("services");
const serviceCollection = database.collection("newServices");
const bookingCollection = database.collection("bookings");
/* auth or jwt related api
app.post('/jwt', logger, async (req, res) => {
const user = req.body;
console.log(user);
Generate Access Token
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1h' });
Set Token in HTTP Only Cookie
res
.cookie('token', token, {
httpOnly: true,
secure: false,
})
.send({ success: true });
}) */
// JWT related API
app.post('/jwt', async (req, res) => {
const user = req.body;
console.log('User for token', user);
// Generate Access Token
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1h' });
// Set Access Token in HTTP Only Cookie
res
.cookie('token', token, {
httpOnly: true,
secure: true,
sameSite: 'none'
})
.send({ success: true });
})
// Clear Cookie after Logging Out
app.post('/logout', async (req, res) => {
const user = req.body;
console.log('Logging Out', user);
res
.clearCookie('token', { maxAge: 0 })
.send({ success: true });
})
// Get all services data
app.get('/services', async (req, res) => {
const filter = req.query;
console.log(filter);
const query = {
title: { $regex: filter.search, $options: 'i' }
};
const options = {
sort: {
price: filter.sort === "asc" ? 1 : -1,
}
};
const cursor = serviceCollection.find(query, options);
const result = await cursor.toArray();
res.send(result);
})
// Get specific service data
app.get('/services/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const options = {
projection: { price: 1, service_id: 1, title: 1, img: 1 },
};
const result = await serviceCollection.findOne(query, options);
res.send(result);
})
// Get some booking data based on criteria (email)
app.get('/bookings', logger, verifyToken, async (req, res) => {
console.log(req.query.email);
// console.log('Access Token', req.cookies.token);
console.log('Owner of the token:', req.user);
if (req.user.email !== req.query.email) {
return res.status(403).send({ message: "forbidden access" });
}
/* console.log('user in the valid token:', req.user);
if (req.user.email !== req.query.email) {
return res.send(403).send({ message: 'forbidden access' });
} */
let query = {};
if (req.query?.email) {
query = { email: req.query.email };
}
const cursor = bookingCollection.find(query);
const result = await cursor.toArray();
res.send(result);
})
// Post (send) booking data
app.post('/bookings', async (req, res) => {
const booking = req.body;
const result = await bookingCollection.insertOne(booking);
res.send(result);
})
// Update (Patch) a specific booking data
app.patch('/bookings/:id', async (req, res) => {
const id = req.params.id;
const booking = req.body;
const filter = { _id: id };
const updatedBooking = {
$set: {
status: booking.status
}
}
const result = await bookingCollection.updateOne(filter, updatedBooking);
res.send(result);
})
// Delete specific booking data
app.delete('/bookings/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: id };
const result = await bookingCollection.deleteOne(query);
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
// await client.close();
}
}
run().catch(console.dir);
app.get('/', (req, res) => {
res.send('Car Doctor server is running');
})
app.listen(port, () => {
console.log(`Car Doctor server is running on PORT: ${port}`);
})