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

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