-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
149 lines (127 loc) · 4.05 KB
/
server.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// Third Party Modules - Dependencies
const pug = require('pug');
const path = require('path');
const http = require('http');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const express = require('express');
const session = require('express-session');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const favicon = require('serve-favicon');
const socketIO = require('socket.io');
// MongoDB Database
let db;
if (process.env.NODE_ENV === 'production') {
db = mongoose.connect('mongodb://kuraforum:kuraforum123@ds129733.mlab.com:29733/kura', {useMongoClient: true});
} else {
db = mongoose.connect('mongodb://127.0.0.1/kura', {useMongoClient : true});
}
// Check for Database connection and errors
db.on('error', (err) => {
console.log(err)
}).once('open', () => {
console.log('Connected to mongoDb')
});
// Socket-IO
let app = express();
var server = http.createServer(app);
var io = socketIO(server);
const port = process.env.PORT || 3000;
let visitorsData = {};
io.on('connection', (socket) => {
socket.on('visitor-data', (data) => {
visitorsData[socket.id] = data;
io.emit('updated-stats', getActiveUsers());
});
socket.on('disconnect', () => {
delete visitorsData[socket.id];
io.emit('updated-stats', getActiveUsers());
});
});
// get the total active users on our site
function getActiveUsers() {
return Object.keys(visitorsData).length;
}
// Load View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Set Local Variables
app.locals.moment = require('moment');
// Body Parser
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json())
// User Static File
app.use(express.static(path.join(__dirname, 'assets')));
// Express Message
app.use(require('connect-flash')());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Express validator middleware
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.');
var root = namespace.shift();
var formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Express Session Middleware
app.use(session({secret: 'kura_forum_123', resave: false, saveUninitialized: false}));
// Serve Favicon
app.use(favicon(path.join(__dirname, 'assets', 'image', 'favicon.png')))
// Check if user is logged in
let UserModel = require('./models/user');
app.use((req, res, next) => {
if (req.session && req.session.user) {
UserModel.findOne({ email: req.session.user.email }, (err, user) => {
if (user) {
req.user = user;
delete req.user.password; // delete the password from the session
req.session.user = user; //refresh the session value
res.locals.user = user;
}
// finishing processing the middleware and run the route
next();
});
} else {
next();
}
});
// Custom Express validator to not allow spaces
app.use(expressValidator({
customValidators: {
noSpaces: function(value) {
return (value.search(' ')) >= 0 ? false : true;
}
}
}));
// Route Files
let indexRoute = require('./routes/index');
let userRoute = require('./routes/user');
let adminRoute = require('./routes/admin');
let answerRoute = require('./routes/answer');
let questionRoute = require('./routes/question');
let searchRoute = require('./routes/search');
app.use('/', indexRoute);
app.use('/user', userRoute);
app.use('/admin', adminRoute);
app.use('/answer', answerRoute);
app.use('/questions', questionRoute);
app.use('/search', searchRoute);
// 404 Errors
app.get('*', (req, res) => {
res.render('info/404_page');
});
server.listen(port, ()=> {
console.log(`Listening at port ${port}`);
});