-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
130 lines (106 loc) · 3.78 KB
/
app.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
const path = require('path')
const express = require('express')
const morgan = require('morgan')
const rateLimit = require('express-rate-limit')
const helmet = require('helmet')
const mongoSanitize = require('express-mongo-sanitize')
const xss = require('xss-clean')
const hpp = require('hpp')
const cookieParser = require('cookie-parser')
const AppError = require('./utils/appError')
const globalErrorHandler = require('./controllers/errorController')
const tourRouter = require('./routes/tourRoutes')
const userRouter = require('./routes/userRoutes')
const reviewRouter = require('./routes/reviewRoutes')
const viewRouter = require('./routes/viewRoutes')
const app = express()
app.set('view engine', 'pug')
// This help us to forget about whether the route has slash or not already
app.set('views', path.join(__dirname, 'views'))
// 1) GLOBAL MIDDLEWARES
// Serving static files
app.use(express.static(path.join(__dirname, 'public')))
// Secure HTTP HEADERS
// In app.use, we always need to pass in a function rather than a function call
// the result of helmet() is exactly a function
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'", 'https:', 'http:', 'data:', 'ws:'],
baseUri: ["'self'"],
fontSrc: ["'self'", 'https:', 'http:', 'data:'],
scriptSrc: ["'self'", 'https:', 'http:', 'blob:'],
styleSrc: ["'self'", "'unsafe-inline'", 'https:', 'http:'],
imgSrc: ["'self'", 'data:', 'blob:'],
},
},
})
)
// Development logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'))
}
// Middleware: function in the middle of request and response, can modify request and response
// Limit requests from same IP
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour!',
})
app.use('/api', limiter)
// Body parser, reading data from body into req.body
app.use(express.json({ limit: '10kb' }))
app.use(express.urlencoded({ extended: true, limit: '10kb' }))
app.use(cookieParser())
// Data sanitization against NoSQL query injection
app.use(mongoSanitize())
// This middleware will remove the dollar sign and dot from the request body and query string
// Data sanitization against XSS
app.use(xss())
// This middleware will clean any user input from malicious HTML code
// Prevent parameter pollution
app.use(
hpp({
// the parameters that we want to allow to be passed multiple times
whitelist: [
'duration',
'ratingsQuantity',
'ratingsAverage',
'maxGroupSize',
'difficulty',
'price',
],
})
)
// This middleware will prevent parameter pollution, which means that if the same parameter is passed multiple times, the last value will be used
// Test middleware
app.use((req, res, next) => {
// console.log('Hello from the middleware 😀')
// console.log(req.cookies)
next()
})
app.use((req, res, next) => {
req.requestTime = new Date().toISOString()
next()
})
// Only the callback function is running in event loop
// 3) ROUTES
app.use('/', viewRouter)
// Mounting a new router on a route
app.use('/api/v1/tours', tourRouter)
app.use('/api/v1/users', userRouter)
app.use('/api/v1/reviews', reviewRouter)
app.all('*', (req, res, next) => {
// res.status(404).json({
// status: 'fail',
// message: `Can't find ${req.originalUrl} on this server!`,
// })
// const err = new Error(`Can't find ${req.originalUrl} on this server!`)
// err.status = 'fail'
// err.statusCode = 404
// next(err)
next(new AppError(`Can't find ${req.originalUrl} on this server!`))
})
app.use(globalErrorHandler)
module.exports = app