-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
350 lines (305 loc) · 8.07 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
// Require Packages
const createError = require('http-errors')
const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
const mongoose = require('mongoose')
const cors = require('cors')
const { DB_URL } = require('./db')
// Build the App
const app = express()
app.set('trust proxy', 1)
// Cors Middlewear
app.use(
cors({
credentials: true,
origin: [
'https://bejewelled-cendol-bdbb84.netlify.app',
'https://abb-copy-react.onrender.com',
'http://localhost:3000',
'http://localhost:3000/login',
'http://localhost:3001',
],
})
)
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(cookieParser())
// Database
mongoose.connect(
DB_URL,
{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false },
() => {
console.log('Connected to MongoDB')
}
)
// Security
require('./express-sessions')(app)
// Models
const Bookings = require('./models/bookings')
const Houses = require('./models/houses')
const Reviews = require('./models/reviews')
const Users = require('./models/users')
const { session } = require('passport')
// Routes
// ::::
app.get('/', async (req, res) => {
console.log(req.query)
let products = await Users.find({})
console.log(products)
res.send('Hello from the Airbnb API')
})
app.get('/houses', async (req, res) => {
try {
let obj = {}
if (req.query.price) {
obj.price = {
$lte: req.query.price,
}
}
// search bar will only work if it is the exact match of the title
if (req.query.search) {
obj.title = req.query.search
}
if (req.query.location) {
obj.location = req.query.location
}
if (req.query.rooms) {
obj.rooms = req.query.rooms
}
// search houses if select options are used
let houses
if (req.query.sort == 1) {
houses = await Houses.find(obj).sort('price')
} else if (req.query.sort == -1) {
houses = await Houses.find(obj).sort('-price')
} else {
houses = await Houses.find(obj)
}
res.send(houses)
} catch (err) {
console.log(err)
}
})
app.get('/houses/:id', async (req, res) => {
// Find the document in the houses collection by _id
let houseId = req.params.id
// Populate its host field
let house = await Houses.findById(houseId).populate('host', 'avatar name')
// Respond with the house object
res.send(house)
})
// POST /houses
app.post('/houses', async (req, res) => {
try {
if (req.isAuthenticated()) {
console.log(req.body)
// set the host to the authenticated user's ID
req.body.host = req.user._id
let house = await Houses.create(req.body)
res.send(house)
} else {
console.log('not auth')
res.send('Not authorized')
}
} catch (err) {
console.log(err)
}
})
// PATCH /houses/:id
app.patch('/houses/:id', (req, res) => {
if (req.isAuthenticated()) {
res.send('patch from houses with ID')
} else {
res.send('Not authorized')
}
})
// DELETE /houses/:id
app.delete('/houses/:id', (req, res) => {
if (req.isAuthenticated()) {
res.send('delete from houses with ID')
} else {
res.send('Not authorized')
}
})
// GET /bookings
app.get('/bookings', async (req, res) => {
let booking = await Bookings.find({ house: req.query.house })
res.send(booking)
})
// POST /bookings
app.post('/bookings', async (req, res) => {
try {
if (req.isAuthenticated()) {
// set the author to the authenticated user's ID
req.body.author = req.user._id
let booking = await Bookings.create(req.body)
res.send(booking)
} else {
console.log('not auth')
res.send('Not authorized')
}
} catch (err) {
console.log(err)
}
})
// GET /reviews
app.get('/reviews', async (req, res) => {
console.log('req query house', req.query)
let reviews = await Reviews.find({ house: req.query.house })
console.log('req body: ', req)
res.send(reviews)
})
// POST /reviews
app.post('/reviews', async (req, res) => {
if (req.isAuthenticated()) {
req.body.author = req.user._id
console.log(req.body)
let review = await Reviews.create(req.body)
res.send(review)
} else {
res.send('Not authorized')
}
})
// get current logged in user by searching database
// GET /profile
app.get('/profile', async (req, res) => {
console.log('In /profile route')
try {
if (req.isAuthenticated) {
console.log('User is authenticated')
// console.log('req.user._id:', req.user._id)
// find current logged in user by searching database
let currentUser = await Users.findOne(req.user)
console.log('currentUser:', currentUser)
res.send(currentUser)
} else {
console.log('User is not authenticated')
res.send('Not authorized')
}
} catch (err) {
console.log(err)
}
})
// PATCH /profile
// Use app.patch /profile route to update the currently logged in user in the database Then respond with the updated user
app.patch('/profile', async (req, res) => {
if (req.isAuthenticated()) {
console.log(req.body)
let currentUser = await Users.findOne(req.user)
console.log(currentUser)
let updatedUser = await Users.findOneAndUpdate(req.name, req.body, {
new: true,
})
// let updatedUser = await Users.findOneAndUpdate(currentUser, req.body, {
// new: true,
// })
console.log(updatedUser)
res.send(updatedUser)
} else {
res.send('Not authorized')
}
})
// POST /login
// app.post('/login', async (req, res) => {
// try {
// // find user that matches email and password
// let userFound = await Users.findOne({
// email: req.body.email,
// password: req.body.password,
// })
// // check if user exits, meaning it does not equal and empty string
// if (!userFound) {
// // #TODO respond with passport
// console.log('Cannot login: User does not exist. Please sign up instead.')
// res.send('Cannot login: User does not exist. Please sign up instead.')
// } else {
// console.log(userFound)
// req.login(userFound, (err) => {
// if (err) {
// return next(err)
// }
// res.send(userFound)
// })
// }
// } catch (err) {
// res.send(err)
// }
// })
// POST /login
app.post('/login', async (req, res) => {
try {
// find user that matches email and password
let userFound = await Users.findOne({
email: req.body.email,
password: req.body.password,
})
// check if user exits, meaning it does not equal and empty string
if (!userFound) {
// #TODO respond with passport
console.log('Cannot login: User does not exist. Please sign up instead.')
res.send('Cannot login: User does not exist. Please sign up instead.')
} else {
console.log(userFound)
req.login(userFound, (err) => {
if (err) {
return next(err)
}
res.send(userFound)
})
}
} catch (err) {
res.send(err)
}
})
// POST /signup
app.post('/signup', async (req, res) => {
try {
let userExists = await Users.findOne({
email: req.body.email,
})
if (!userExists) {
let user = await Users.create(req.body)
console.log(req.body)
res.send(user)
} else {
console.log('User with this email already exists')
res.send('User with this email already exists')
}
} catch (err) {
res.send(err)
}
})
// GET /logout
app.get('/logout', async (req, res) => {
console.log('ok')
req.logout(function (err) {
if (err) {
return next(err)
}
req.session.destroy(function (err) {
if (err) {
return next(err)
}
res.clearCookie('connect.sid')
res.send('Logged out')
})
})
})
// ::::
// Catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404))
})
// Error Handler
app.use((err, req, res, next) => {
// Respond with an error
res.status(err.status || 500)
res.send({
message: err,
})
})
module.exports = app