server.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. // ===========================================
  2. // REQUARKS WIKI
  3. // 1.0.0
  4. // Licensed under AGPLv3
  5. // ===========================================
  6. global.ROOTPATH = __dirname;
  7. global.PROCNAME = 'SERVER';
  8. // ----------------------------------------
  9. // Load Winston
  10. // ----------------------------------------
  11. var _isDebug = process.env.NODE_ENV === 'development';
  12. global.winston = require('./lib/winston')(_isDebug);
  13. winston.info('[SERVER] Requarks Wiki is initializing...');
  14. // ----------------------------------------
  15. // Load global modules
  16. // ----------------------------------------
  17. var appconfig = require('./models/config')('./config.yml');
  18. global.lcdata = require('./models/localdata').init(appconfig, 'server');
  19. global.db = require('./models/db')(appconfig);
  20. global.git = require('./models/git').init(appconfig, false);
  21. global.entries = require('./models/entries').init(appconfig);
  22. global.mark = require('./models/markdown');
  23. // ----------------------------------------
  24. // Load modules
  25. // ----------------------------------------
  26. var _ = require('lodash');
  27. var express = require('express');
  28. var path = require('path');
  29. var favicon = require('serve-favicon');
  30. var session = require('express-session');
  31. var lokiStore = require('connect-loki')(session);
  32. var cookieParser = require('cookie-parser');
  33. var bodyParser = require('body-parser');
  34. var flash = require('connect-flash');
  35. var compression = require('compression');
  36. var passport = require('passport');
  37. var autoload = require('auto-load');
  38. var expressValidator = require('express-validator');
  39. var http = require('http');
  40. global.lang = require('i18next');
  41. var i18next_backend = require('i18next-node-fs-backend');
  42. var i18next_mw = require('i18next-express-middleware');
  43. var mw = autoload(path.join(ROOTPATH, '/middlewares'));
  44. var ctrl = autoload(path.join(ROOTPATH, '/controllers'));
  45. // ----------------------------------------
  46. // Define Express App
  47. // ----------------------------------------
  48. global.app = express();
  49. // ----------------------------------------
  50. // Security
  51. // ----------------------------------------
  52. app.use(mw.security);
  53. // ----------------------------------------
  54. // Passport Authentication
  55. // ----------------------------------------
  56. var strategy = require('./models/auth')(passport, appconfig);
  57. app.use(cookieParser());
  58. app.use(session({
  59. name: 'requarkswiki.sid',
  60. store: new lokiStore({ path: path.join(appconfig.datadir.db, 'sessions.db') }),
  61. secret: appconfig.sessionSecret,
  62. resave: false,
  63. saveUninitialized: false
  64. }));
  65. app.use(flash());
  66. app.use(passport.initialize());
  67. app.use(passport.session());
  68. // ----------------------------------------
  69. // Localization Engine
  70. // ----------------------------------------
  71. lang
  72. .use(i18next_backend)
  73. .use(i18next_mw.LanguageDetector)
  74. .init({
  75. load: 'languageOnly',
  76. ns: ['common'],
  77. defaultNS: 'common',
  78. saveMissing: false,
  79. supportedLngs: ['en', 'fr'],
  80. preload: ['en', 'fr'],
  81. fallbackLng : 'en',
  82. backend: {
  83. loadPath: './locales/{{lng}}/{{ns}}.json'
  84. }
  85. });
  86. // ----------------------------------------
  87. // View Engine Setup
  88. // ----------------------------------------
  89. app.use(compression());
  90. app.use(i18next_mw.handle(lang));
  91. app.set('views', path.join(ROOTPATH, 'views'));
  92. app.set('view engine', 'pug');
  93. app.use(favicon(path.join(ROOTPATH, 'assets', 'favicon.ico')));
  94. app.use(bodyParser.json());
  95. app.use(bodyParser.urlencoded({ extended: false }));
  96. app.use(expressValidator());
  97. // ----------------------------------------
  98. // Public Assets
  99. // ----------------------------------------
  100. app.use(express.static(path.join(ROOTPATH, 'assets')));
  101. // ----------------------------------------
  102. // View accessible data
  103. // ----------------------------------------
  104. app.locals._ = require('lodash');
  105. app.locals.moment = require('moment');
  106. app.locals.appconfig = appconfig;
  107. app.use(mw.flash);
  108. // ----------------------------------------
  109. // Controllers
  110. // ----------------------------------------
  111. app.use('/', ctrl.auth);
  112. app.use('/uploads', ctrl.uploads);
  113. app.use('/admin', mw.auth, ctrl.admin);
  114. app.use('/', ctrl.pages);
  115. // ----------------------------------------
  116. // Error handling
  117. // ----------------------------------------
  118. // catch 404 and forward to error handler
  119. app.use(function(req, res, next) {
  120. var err = new Error('Not Found');
  121. err.status = 404;
  122. next(err);
  123. });
  124. // error handlers
  125. app.use(function(err, req, res, next) {
  126. res.status(err.status || 500);
  127. res.render('error', {
  128. message: err.message,
  129. error: _isDebug ? err : {}
  130. });
  131. });
  132. // ----------------------------------------
  133. // Start HTTP server
  134. // ----------------------------------------
  135. winston.info('[SERVER] Starting HTTP server on port ' + appconfig.port + '...');
  136. app.set('port', appconfig.port);
  137. var server = http.createServer(app);
  138. server.listen(appconfig.port);
  139. server.on('error', (error) => {
  140. if (error.syscall !== 'listen') {
  141. throw error;
  142. }
  143. // handle specific listen errors with friendly messages
  144. switch (error.code) {
  145. case 'EACCES':
  146. console.error('Listening on port ' + appconfig.port + ' requires elevated privileges!');
  147. process.exit(1);
  148. break;
  149. case 'EADDRINUSE':
  150. console.error('Port ' + appconfig.port + ' is already in use!');
  151. process.exit(1);
  152. break;
  153. default:
  154. throw error;
  155. }
  156. });
  157. server.on('listening', () => {
  158. winston.info('[SERVER] HTTP server started successfully! [RUNNING]');
  159. });
  160. // ----------------------------------------
  161. // Start child processes
  162. // ----------------------------------------
  163. var fork = require('child_process').fork,
  164. libInternalAuth = require('./lib/internalAuth');
  165. global.WSInternalKey = libInternalAuth.generateKey();
  166. var wsSrv = fork('ws-server.js', [WSInternalKey]),
  167. bgAgent = fork('agent.js', [WSInternalKey]);
  168. process.on('exit', (code) => {
  169. wsSrv.disconnect();
  170. bgAgent.disconnect();
  171. });
  172. // ----------------------------------------
  173. // Connect to local WebSocket server
  174. // ----------------------------------------
  175. var wsClient = require('socket.io-client');
  176. global.ws = wsClient('http://localhost:' + appconfig.wsPort, { reconnectionAttempts: 10 });
  177. ws.on('connect', function () {
  178. winston.info('[SERVER] Connected to WebSocket server successfully!');
  179. });
  180. ws.on('connect_error', function () {
  181. winston.warn('[SERVER] Unable to connect to WebSocket server! Retrying...');
  182. });
  183. ws.on('reconnect_failed', function () {
  184. winston.error('[SERVER] Failed to reconnect to WebSocket server too many times! Stopping...');
  185. process.exit(1);
  186. });