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