-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
79 lines (71 loc) · 2.35 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
require('dotenv').config();
const mysql = require('mysql2/promise');
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const logger = require('morgan');
const methodOverride = require('method-override');
const session = require('express-session');
const flash = require('connect-flash');
const passport = require('passport');
const initializePassport = require('./config/passport');
initializePassport(passport);
const MySQLStore = require('express-mysql-session')(session);
const Models = require('./models');
const app = express();
// View Engine Setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const options = {
host: process.env.DB_HOSTNAME,
port: 3306,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
};
const connection = mysql.createPool(options);
const sessionStore = new MySQLStore({}, connection);
app.use(
session({
secret: 'secret',
resave: true,
store: sessionStore,
saveUninitialized: false
}),
);
app.use(cookieParser());
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use(methodOverride('_method'));
app.use(csrf({ cookie: true }));
app.use( async (req, res, next) => {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.locals.csrfToken = req.csrfToken();
res.locals.old = req.flash('old')[0] || '';
res.locals.messages = req.flash();
res.locals.user = req.user;
res.locals.currentUrl = (req.protocol + '://' + req.get('host') + req.originalUrl).split('/').splice(2, 2);
res.locals.districtActive = await Models.district.findOne({ where: { isActive: 1 } }) || '' ;
next();
})
// Routes
require('./routes')(app, passport);
app.get('/failure', (req, res) => res.render('errors/errorPromise'));
app.use(function(req, res, next) {
next(createError(404));
});
// Error handler
app.use(function(err, req, res, next) {
res.locals.messageSystem = err.message;
res.locals.errorSystem = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('errors/error');
});
module.exports = app;