-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
267 lines (226 loc) · 6.62 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
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
require('newrelic');
var fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var exprSession = require('express-session');
var mongoose = require('mongoose');
var passport = require('passport');
var favicon = require('serve-favicon');
var flash = require('connect-flash');
var log = require('./core/logging')('core');
var app = module.exports = express();
app.data = null;
try {
// Check if config.json exists
fs.lstatSync('./config.json');
app.data = (JSON.parse(fs.readFileSync('./config.json', 'utf8')));
}
catch (e) {
// Read config from env var
app.data = (JSON.parse(process.env.config));
log.warning('Using config from env var.')
}
// List of enabled and available modules and games
var available_games = [];
var available_modules = [];
// Used theme
var used_theme = null;
for (var theme in app.data.themes) {
if (app.data.themes[theme]) {
used_theme = theme;
}
}
// Init db connection
var configDB = require('./config/database.js');
// Skip mongoose deprication warning on startup:
// Mongoose: mpromise (mongoose's default promise library) is deprecated, plug
// in your own promise library instead: http://mongoosejs.com/docs/promises.html
mongoose.Promise = global.Promise;
mongoose.connection.on('error', configDB.check);
// Connect to proper db
if (process.env.NODE_ENV == 'production') {
mongoose.connect(app.data.mongo_url.prod)
} else if (process.env.NODE_ENV == 'testing'){
mongoose.connect(app.data.mongo_url.test)
} else {
mongoose.connect(app.data.mongo_url.dev)
}
// Require db schemas
var Settings = require('./config/models/settings');
var Tag = require('./config/models/tag');
var Event = require('./config/models/event');
var Badges = require('./config/models/badges');
// Ensure superuser exists
var User = require('./config/models/user');
// Get first superuser from config dict
var root = Object.keys(app.data.superuser)[0];
var pass = app.data.superuser[root];
// Add to users collection only if does not already exist
var update = { $set: {
'role' : 0,
'local.username' : 'root',
'local.email' : root,
'local.password' : new User().generateHash(pass)
}}
User.update({'local.email': root}, update, {upsert: true}).exec(function() {})
// Enable local login by default
Settings.findOne({'key': 'login-local'}).exec(function (err, num) {
if (!num) new Settings({
'key': 'login-local',
'val': true
}).save()
})
// Add test accounts in development or testing
if (process.env.NODE_ENV != 'development' || process.env.NODE_ENV != 'testing') {
require('./core/demo.js');
}
// Configuring Passport
require('./core/auth')(app, passport)
// Init badges
query = {'name': 'qotd-streak'}
update = {$set: {'levels': [{
'name' : 'I',
'limit' : 5
}, {
'name' : 'II',
'limit' : 20
}]}}
Badges.update(query, update, {upsert: true}).exec(function (err) {
if (err) log.error('Could not init badges.')
})
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(flash())
app.use(bodyParser.json())
app.use('/public', express.static(__dirname + '/public'))
app.use('/modules', express.static(__dirname + '/modules'))
app.use('/theme', express.static(__dirname + '/node_modules/' + used_theme))
app.use(favicon('public/img/favicon.ico'))
app.use(exprSession({
secret : 'MySecret',
name : "mycookie",
resave : true,
saveUninitialized : true,
cookie: {
secure: false,
maxAge: 1800000 //30 min
}
}))
app.use(passport.initialize())
app.use(passport.session())
// Localization
var i18n = require('i18n-2')
i18n.expressBind(app, {
// setup some locales
locales: ['ro', 'en'],
// set the default locale
defaultLocale: 'en',
// set location
directory: './node_modules/' + used_theme + '/locales',
extension: '.json',
// do not automatically resolve unknown strings
devMode: false
})
// Store available views
// Views in the themes directory have the highest priority and can overwrite
// core or module views
views = ['views', './node_modules/' + used_theme + '/views']
// Auto login with dummy user in development if 'login'
// argument is provided
app.use(function (req, res, next) {
if (req.app.get('env') == 'development' && process.argv[2] == 'login') {
req.user = {
'_id': '000000000000000000000000',
'name': 'Dev User',
'email': '[email protected]',
'role': 0,
'facebook': {
'id': 0
},
'twitter': {
'id': 0
},
'google': {
'id': 0
},
'github': {
'id': 0
},
'local': {
'email': '[email protected]'
}
}
}
return next()
})
app.use(function (req, res, next) {
log.debug(req.method + ' ' + req.url)
// Save selected role to session
if (req.query.role) {
req.session.ROLE = req.query.role
}
// Transfer vars to view
res.locals.ROLE = req.session.ROLE
res.locals.URL = req.url.split('?')[0]
// Set preferred locale
req.i18n.setLocale(req.app.data.language)
next()
})
// Load enabled games
for (game in app.data.games) {
if (app.data.games[game]) {
// Build list of enabled modules
available_games.push(game)
// Load module shema, if exists
// Modules such as wouso-social-login do not provide any shema
try {
require(game + '/model.js')
} catch (err) {}
// Load module routes
app.use(require(game + '/routes.js'))
// Load module views
views.push('node_modules/' + game)
}
}
// Load enabled modules
for (module in app.data.modules) {
if (app.data.modules[module]) {
// Build list of enabled modules
available_modules.push(module)
// Load module shema, if exists
// Modules such as wouso-social-login do not provide any shema
try {
require(module + '/model.js')
} catch (err) {}
// Load module routes
app.use(require(module + '/routes.js'))
// Load module views
views.push('node_modules/' + module)
}
}
// Load core routes
var routes_dir = './routes'
var routes = fs.readdirSync(routes_dir);
for (var i in routes) {
var route = routes_dir + '/' + routes[i]
// Load middleware in the end
if (route != './routes/base.js')
app.use(require(route))
}
// Load middleware
app.use(require('./routes/base'))
// Set app settings
app.set('views', views)
app.set('view engine', 'pug')
app.set('modules', available_modules)
app.set('games', available_games)
app.set('theme', used_theme)
// Pretty print html rendered with Jade
app.locals.pretty = true
// Launch server
if (process.env.NODE_ENV != 'testing') {
server = app.listen(process.env.PORT || 4000, function() {
log.notice('Server listening on port 4000')
})
}