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.

236 lines
6.4 KiB

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