You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

240 lines
6.6 KiB

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