-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
92 lines (72 loc) · 2.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
'use strict';
// use dotenv if not in production
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const express = require('express');
const session = require('express-session');
const flash = require('connect-flash');
const passport = require('passport');
const methodOverride = require('method-override');
const favicon = require('serve-favicon');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 8000;
// Routes Handlers
const routeHandler = require('./routes/index');
// Rate limiter middleware
const rateLimiterMiddleware = require('./middlewares/ratelimiter');
// Mongoose Config
require('./config/database');
// Passport
require('./config/passport')(passport);
// Body parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Set view engine
app.set('view engine', 'ejs');
// Tell express to use the public directory
app.use(express.static(path.join(__dirname + '/public')));
// Utility functions to be used in templates
app.locals.date = require('./utils/date');
// Express Sessions
// TODO: Use MongoStore or RedisStore for production
app.use(
session({
name: 'crypt_sid',
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
}),
);
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Connect flash
app.use(flash());
app.use(rateLimiterMiddleware);
// Security
// TODO: add helmet
// app.use(helmet());
// Method override
app.use(
methodOverride(function (req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
let method = req.body._method;
delete req.body._method;
return method;
}
}),
);
// Global Variables
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
// Routes
app.use(routeHandler);
// 404s
app.get('*', (req, res) => {
res.render('errors/404');
});
app.listen(PORT, console.log(`Server started on port ${PORT}`));