-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
100 lines (81 loc) · 2.27 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
const express = require('express');
const app = express();
require('dotenv').config();
const passport = require('passport');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const flash = require('connect-flash');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const favicon = require('serve-favicon');
const path = require('path');
const server = require('http').Server(app);
const LocalStrategy = require('passport-local').Strategy;
const userreg = require('./models/userreg');
// MongoDB Atlas Connection String from environment variables
const { ATLAS_URI } = process.env;
// static
app.use('/public', express.static('public'));
app.use(
// eslint-disable-next-line no-undef
favicon(path.join(__dirname, './public/img', 'onlinetb_favi.ico'))
);
// bodyparser
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
// cookies
app.use(cookieParser());
// flash
app.use(flash());
// EJS
app.set('view engine', 'ejs');
// sessions
app.use(
session({
secret: 'its a secret',
resave: false,
saveUninitialized: false,
})
);
// MongoDB Setup and Connection
mongoose.connect(ATLAS_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'Connection Error'));
db.once('open', () => {
console.log('OnlineTextbooksDB Connected Successfully');
});
// passport
app.use(passport.initialize());
app.use(passport.session());
// passport config
passport.serializeUser(userreg.serializeUser());
passport.deserializeUser(userreg.deserializeUser());
passport.use(
new LocalStrategy({ usernameField: 'email' }, userreg.authenticate())
);
// disable cache
app.use((req, res, done) => {
res.set(
'Cache-Control',
'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
);
done();
});
// routes
app.use('/users', require('./routes/user'));
app.use('/', require('./routes/index'));
// handle 404 and 500 error
app.use((req, res) => {
res.status(404);
res.render('404');
});
app.use((req, res) => {
res.status(500);
res.render('500');
});
const port = process.env.PORT || 3000;
server.listen(port, () => console.log(`Listening on port ${port}`));