-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
95 lines (87 loc) · 2.66 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
// node modules
const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const session = require('express-session');
const flash = require('express-flash');
const MongoStore = require('connect-mongo');
const passport = require('passport');
const layout = require('express-ejs-layouts');
const errorHandler = require('errorhandler');
const config = require('./config/config')[process.env.NODE_ENV || 'development'];
const logger = require('./config/logger').init('MASTER');
const log = require('morgan');
const chalk = require('chalk');
require('dotenv').config();
// database connection
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect(process.env.DATABASE_URI || 'mongodb://localhost:27020/test', () => {
logger.info(`${chalk.green('✓')} Database Connection Successful`);
});
mongoose.connection.on('error', (err) => {
logger.error('Database Connection Error');
logger.error(err);
logger.error(`${chalk.red('✗')} MongoDB connection error. Please make sure MongoDB is running`);
process.exit();
});
app.use(layout);
app.set('layout', './v1/layout');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(log('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(
session({
key: 'doc-ops',
secret: config.secret,
store: MongoStore.create({
mongoUrl: process.env.DATABASE_URI,
}),
}),
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.disable('x-powered-by');
app.use((req, res, next) => {
if (
!req.user &&
req.path !== '/login' &&
req.path !== '/signup' &&
!req.path.match(/^\/auth/) &&
!req.path.match(/\./)
) {
req.session.return_to = req.originalUrl;
} else if (req.user && (req.path === '/account' || req.path.match(/^\/api/))) {
req.session.return_to = req.originalUrl;
}
next();
});
app.use(express.static(path.join(__dirname, 'public')));
// set local variables
app.use((req, res, next) => {
req.client_ip = req.socket.remoteAddress;
// for views
res.locals.client_ip = req.client_ip;
res.locals.current_user = req.user;
next();
});
// setting router
app.use(require('./routes'));
/**
* Error Handler.
*/
if (process.env.NODE_ENV === 'development') {
app.use(errorHandler());
} else {
app.use((err, req, res, next) => {
logger.error(err);
res.status(500).send('Server Error');
});
}
module.exports = app;