-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
326 lines (291 loc) · 7.67 KB
/
index.js
File metadata and controls
326 lines (291 loc) · 7.67 KB
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
// Import required modules
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const JWT = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const imageDownloader = require("image-downloader");
const path = require("path");
const multer = require("multer");
const fs = require("fs");
// Import models
const User = require("./models/Users");
const Place = require("./models/Place");
const Booking = require("./models/Booking");
// App configuration
require("dotenv").config();
const app = express();
const bcryptSalt = bcrypt.genSaltSync(12);
const jwtSecret = "asdvavszvawfd";
// Middleware
app.use(express.json());
app.use(cookieParser());
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
app.use(
cors({
origin:
["https://bright-chebakia-be5e03.netlify.app"],
credentials: true,
})
);
// Database connection
async function startServer() {
try {
await mongoose.connect(process.env.MONGO_URL);
console.log("Connected to the Database");
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
} catch (err) {
console.error("Could not connect to the database.", err);
}
}
// Utility function to get user data from token
function getUserDataFromToken(req) {
return new Promise((resolve, reject) => {
JWT.verify(req.cookies.token, jwtSecret, {}, async (err, user) => {
if (err) reject(err);
resolve(user);
});
});
}
// Route for simple test
app.get("/test", (req, res) => {
res.json("test ok");
});
// User registration
app.post("/register", async (req, res) => {
const { name, email, password } = req.body;
try {
const user = await User.create({
name,
email,
password: bcrypt.hashSync(password, bcryptSalt),
});
res.json({ user });
} catch (error) {
res.status(422).json(error);
}
});
mongoose
.connect(process.env.MONGO_URL)
.then(() => {
console.log("Connected to the Database");
})
.catch((error) => {
console.log("Not able to connect to the database.", error);
});
// User login
app.post("/login", async (req, res) => {
const { email, password } = req.body;
const isUserExist = await User.findOne({ email });
if (isUserExist) {
const isPasswordCheck = bcrypt.compareSync(password, isUserExist.password);
if (isPasswordCheck) {
JWT.sign(
{ email: isUserExist.email, id: isUserExist._id },
jwtSecret,
{},
(err, token) => {
if (err) throw err;
res.cookie("token", token).json(isUserExist);
}
);
} else {
res.status(422).json("Password not matching");
}
} else {
res.json("User does not exist");
}
});
// Get user profile
app.get("/profile", (req, res) => {
const { token } = req.cookies;
if (token) {
JWT.verify(token, jwtSecret, {}, async (err, user) => {
if (err) throw err;
const { name, email, _id } = await User.findById(user.id);
res.json({ name, email, _id });
});
} else {
res.json(null);
}
});
// User logout
app.post("/logout", (req, res) => {
res.cookie("token", "").json(true);
});
// Upload by link
app.post("/upload-by-link", async (req, res) => {
const { link } = req.body;
if (!link) {
return res.status(400).json({ error: "The link is required" });
}
const newName = "photos" + Date.now() + ".jpg";
try {
await imageDownloader.image({
url: link,
dest: path.join(__dirname, "/uploads/", newName),
});
res.json({ path: "uploads/" + newName });
} catch (err) {
console.error("Error loading the image: ", err);
res.status(500).json({ error: "Failed to download image" });
}
});
// Upload using multer
const photosMiddleware = multer({ dest: "uploads/" });
app.post("/upload", photosMiddleware.array("photos", 100), (req, res) => {
const uploadedFiles = req.files.map((file) => {
const { path, originalname } = file;
const parts = originalname.split(".");
const ext = parts.pop();
const newpath = `${path}.${ext}`;
fs.renameSync(path, newpath);
return newpath.replace("uploads/", "");
});
res.json(uploadedFiles);
});
// Create a new place
app.post("/places", async (req, res) => {
const { token } = req.cookies;
let {
title,
address,
photos,
description,
perks,
extraInfo,
checkIn,
checkOut,
maxGuests,
price,
} = req.body;
photos = req.files.map((file) => file.path.replace("uploads/", ""));
const userData = await getUserDataFromToken(req);
const placeDoc = await Place.create({
owner: userData.id,
title,
address,
photos,
description,
perks,
extraInfo,
checkIn,
checkOut,
maxGuests,
price,
});
res.json(placeDoc);
});
// Get places by user
app.get("/user-places", (req, res) => {
const { token } = req.cookies;
// Check if the token exists
if (!token) {
return res.status(401).json({ message: "No token provided, authorization denied" });
}
JWT.verify(token, jwtSecret, {}, (err, decoded) => {
if (err) {
// Handle the error if token verification fails
return res.status(401).json({ message: "Token is not valid" });
} else {
// Proceed with finding places owned by the user
Place.find({ owner: decoded.id })
.then(places => res.json(places))
.catch(error => res.status(500).json({ message: "Error fetching places", error }));
}
});
});
// app.get("/user-places", async (req, res) => {
// const {token} = req.cookies;
// JWT.verify(token, jwtSecret, {}, async (err, userData) => {
// if(err) return null;
// res.json( await Place.find({owner:userData.id}) );
// });
// });
// Get a specific place by ID
app.get("/places/:id", async (req, res) => {
const { id } = req.params;
res.json(await Place.findById(id));
});
// Update a place
app.put("/places", async (req, res) => {
const { token } = req.cookies;
const {
id,
title,
address,
photos,
description,
perks,
extraInfo,
checkIn,
checkOut,
maxGuests,
price,
} = req.body;
const userData = await getUserDataFromToken(req);
const placeDoc = await Place.findById(id);
if (userData.id === placeDoc.owner.toString()) {
placeDoc.set({
title,
address,
photos,
description,
perks,
extraInfo,
checkIn,
checkOut,
maxGuests,
price,
});
await placeDoc.save();
res.json("Update successful");
} else {
res.status(403).json("Unauthorized");
}
});
// Get all places
app.get("/places", async (req, res) => {
res.json(await Place.find());
});
// Create a booking
app.post("/bookings", async (req, res) => {
const userData = await getUserDataFromToken(req);
const { checkIn, checkOut, place, maxGuests, phone, name, price } = req.body;
try {
const booking = await Booking.create({
checkIn,
checkOut,
place,
maxGuests,
phone,
name,
price,
user: userData.id,
});
res.json(booking);
} catch (e) {
res.status(500).json(e);
}
});
// Get bookings for a user
app.get("/bookings", async (req, res) => {
const userData = await getUserDataFromToken(req);
res.json(await Booking.find({ user: userData.id }).populate("place"));
});
startServer();
// Start server
const PORT = process.env.PORT || 4000;
// const server = app
// .listen(PORT, () => {
// console.log(`Server started on port ${PORT}`);
// })
// .on("error", (err) => {
// if (err.code === "EADDRINUSE") {
// console.error("Port", PORT, "already in use");
// process.exit(1); // Or try a different port
// } else {
// console.error(err);
// }
// });