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.

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