-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
134 lines (123 loc) · 3.89 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
131
132
133
134
// ! Env Variables
import dotenv from 'dotenv';
if (process.env.NODE_ENV !== 'production') {
dotenv.config();
}
// ! Evn Variables
// ************* Import ****************
import express from 'express';
import path from 'path';
import mongoose from 'mongoose';
import methodOverride from 'method-override';
import logger from 'morgan';
import ejsMate from 'ejs-mate';
import { ExpressError } from './utils/ExpressError.js';
import session from 'express-session';
import flash from 'connect-flash';
import passport from 'passport';
import LocalStrategy from 'passport-local';
import User from './models/User.js';
import mongoSanitize from 'express-mongo-sanitize';
import helmet from 'helmet';
import MongoStore from 'connect-mongo';
import moment from 'moment';
// *********** App Configuration ***********
const app = express();
import {
connectSrcUrls,
fontSrcUrls,
scriptSrcUrls,
styleSrcUrls,
} from './utils/allowedSites.js';
// ? *** DB connections ******
mongoose.set('strictQuery', true);
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB Connection Error'));
db.on('open', () => console.log('>>>> DB Connected <<<<'));
// ? *** DB connections ******
// Middlewares
app.use(logger('dev'));
app.engine('ejs', ejsMate);
app.set('view engine', 'ejs');
app.set(path.join('views'));
app.use(express.static(path.join('public')));
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(
session({
// ? setting up session
store: MongoStore.create({ mongoUrl: process.env.MONGODB_URI }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
name: 'YelpCamp-sid',
cookie: {
httpOnly: true,
// secure: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7, // ? 1 week
maxAge: 1000 * 60 * 60 * 24 * 7,
},
})
);
app.use(flash());
app.use(mongoSanitize({ replaceWith: '__' }));
// ! Security Policies
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: [],
connectSrc: ["'self'", ...connectSrcUrls],
scriptSrc: ["'unsafe-inline'", "'self'", ...scriptSrcUrls],
styleSrc: ["'self'", "'unsafe-inline'", ...styleSrcUrls],
workerSrc: ["'self'", 'blob:'],
objectSrc: [],
imgSrc: [
"'self'",
'blob:',
'data:',
process.env.ALLOWED_IMG_STORAGE, //SHOULD MATCH YOUR CLOUDINARY ACCOUNT!
'https://images.unsplash.com/',
],
fontSrc: ["'self'", ...fontSrcUrls],
},
})
);
// *** AUTHENTICATION MIDDLEWARE ***
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.locals.moment = moment;
app.use((req, res, next) => {
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
res.locals.currentUser = req.user;
next();
});
// Unmounting routes
import indexRoutes from './routers/index.js';
import campRoutes from './routers/campgrounds.js';
import reviewRoutes from './routers/reviews.js';
import authRoutes from './routers/auths.js';
import usersRoutes from './routers/users.js';
app.use(indexRoutes);
app.use('/campgrounds', campRoutes);
app.use('/campgrounds/:id/reviews', reviewRoutes);
app.use('/auth', authRoutes);
app.use('/user', usersRoutes);
app.all('*', (req, res, next) => {
next(new ExpressError('Page Not Found', 404));
});
// Error Handlers
app.use((err, req, res, next) => {
const { statusCode = 500 } = err;
res.status(statusCode);
res.render('error', { err });
});
// App Listeners
app.listen(process.env.PORT, () => console.log('YelpCamp Server has Started'));