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.

217 lines
5.8 KiB

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