index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. const debug = require('debug')('growi:crowi');
  2. const logger = require('@alias/logger')('growi:crowi');
  3. const pkg = require('@root/package.json');
  4. const InterceptorManager = require('@commons/service/interceptor-manager');
  5. const CdnResourcesService = require('@commons/service/cdn-resources-service');
  6. const Xss = require('@commons/service/xss');
  7. const path = require('path');
  8. const sep = path.sep;
  9. const mongoose = require('mongoose');
  10. const models = require('../models');
  11. function Crowi(rootdir) {
  12. const self = this;
  13. this.version = pkg.version;
  14. this.runtimeVersions = undefined; // initialized by scanRuntimeVersions()
  15. this.rootDir = rootdir;
  16. this.pluginDir = path.join(this.rootDir, 'node_modules') + sep;
  17. this.publicDir = path.join(this.rootDir, 'public') + sep;
  18. this.libDir = path.join(this.rootDir, 'src/server') + sep;
  19. this.eventsDir = path.join(this.libDir, 'events') + sep;
  20. this.viewsDir = path.join(this.libDir, 'views') + sep;
  21. this.resourceDir = path.join(this.rootDir, 'resource') + sep;
  22. this.localeDir = path.join(this.resourceDir, 'locales') + sep;
  23. this.tmpDir = path.join(this.rootDir, 'tmp') + sep;
  24. this.cacheDir = path.join(this.tmpDir, 'cache');
  25. this.config = {};
  26. this.configManager = null;
  27. this.searcher = null;
  28. this.mailer = {};
  29. this.passportService = null;
  30. this.globalNotificationService = null;
  31. this.slackNotificationService = null;
  32. this.xssService = null;
  33. this.aclService = null;
  34. this.appService = null;
  35. this.fileUploadService = null;
  36. this.restQiitaAPIService = null;
  37. this.cdnResourcesService = new CdnResourcesService();
  38. this.interceptorManager = new InterceptorManager();
  39. this.xss = new Xss();
  40. this.tokens = null;
  41. this.models = {};
  42. this.env = process.env;
  43. this.node_env = this.env.NODE_ENV || 'development';
  44. this.port = this.env.PORT || 3000;
  45. this.events = {
  46. user: new (require(`${self.eventsDir}user`))(this),
  47. page: new (require(`${self.eventsDir}page`))(this),
  48. search: new (require(`${self.eventsDir}search`))(this),
  49. bookmark: new (require(`${self.eventsDir}bookmark`))(this),
  50. tag: new (require(`${self.eventsDir}tag`))(this),
  51. };
  52. }
  53. function getMongoUrl(env) {
  54. return env.MONGOLAB_URI // for B.C.
  55. || env.MONGODB_URI // MONGOLAB changes their env name
  56. || env.MONGOHQ_URL
  57. || env.MONGO_URI
  58. || ((process.env.NODE_ENV === 'test') ? 'mongodb://localhost/growi_test' : 'mongodb://localhost/growi');
  59. }
  60. Crowi.prototype.init = async function() {
  61. await this.setupDatabase();
  62. await this.setupModels();
  63. await this.setupSessionConfig();
  64. await this.setupConfigManager();
  65. // customizeService depends on AppService and XssService
  66. // passportService depends on appService
  67. // slack depends on setUpSlacklNotification
  68. await Promise.all([
  69. this.setUpApp(),
  70. this.setUpXss(),
  71. this.setUpSlacklNotification(),
  72. ]);
  73. await Promise.all([
  74. this.scanRuntimeVersions(),
  75. this.setupPassport(),
  76. this.setupSearcher(),
  77. this.setupMailer(),
  78. this.setupSlack(),
  79. this.setupCsrf(),
  80. this.setUpGlobalNotification(),
  81. this.setUpFileUpload(),
  82. this.setUpAcl(),
  83. this.setUpCustomize(),
  84. this.setUpRestQiitaAPI(),
  85. ]);
  86. };
  87. Crowi.prototype.isPageId = function(pageId) {
  88. if (!pageId) {
  89. return false;
  90. }
  91. if (typeof pageId === 'string' && pageId.match(/^[\da-f]{24}$/)) {
  92. return true;
  93. }
  94. return false;
  95. };
  96. Crowi.prototype.setConfig = function(config) {
  97. this.config = config;
  98. };
  99. Crowi.prototype.getConfig = function() {
  100. return this.config;
  101. };
  102. Crowi.prototype.getEnv = function() {
  103. return this.env;
  104. };
  105. // getter/setter of model instance
  106. //
  107. Crowi.prototype.model = function(name, model) {
  108. if (model != null) {
  109. this.models[name] = model;
  110. }
  111. return this.models[name];
  112. };
  113. // getter/setter of event instance
  114. Crowi.prototype.event = function(name, event) {
  115. if (event) {
  116. this.events[name] = event;
  117. }
  118. return this.events[name];
  119. };
  120. Crowi.prototype.setupDatabase = function() {
  121. // mongoUri = mongodb://user:password@host/dbname
  122. mongoose.Promise = global.Promise;
  123. const mongoUri = getMongoUrl(this.env);
  124. return mongoose.connect(mongoUri, { useNewUrlParser: true });
  125. };
  126. Crowi.prototype.setupSessionConfig = function() {
  127. const self = this;
  128. const session = require('express-session');
  129. const sessionAge = (1000 * 3600 * 24 * 30);
  130. const redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URI || this.env.REDIS_URL || null;
  131. const mongoUrl = getMongoUrl(this.env);
  132. let sessionConfig;
  133. return new Promise(((resolve, reject) => {
  134. sessionConfig = {
  135. rolling: true,
  136. secret: self.env.SECRET_TOKEN || 'this is default session secret',
  137. resave: false,
  138. saveUninitialized: true,
  139. cookie: {
  140. maxAge: sessionAge,
  141. },
  142. };
  143. if (self.env.SESSION_NAME) {
  144. sessionConfig.name = self.env.SESSION_NAME;
  145. }
  146. // use Redis for session store
  147. if (redisUrl) {
  148. const RedisStore = require('connect-redis')(session);
  149. sessionConfig.store = new RedisStore({ url: redisUrl });
  150. }
  151. // use MongoDB for session store
  152. else {
  153. const MongoStore = require('connect-mongo')(session);
  154. sessionConfig.store = new MongoStore({ url: mongoUrl });
  155. }
  156. self.sessionConfig = sessionConfig;
  157. resolve();
  158. }));
  159. };
  160. Crowi.prototype.setupConfigManager = async function() {
  161. const ConfigManager = require('../service/config-manager');
  162. this.configManager = new ConfigManager(this.model('Config'));
  163. return this.configManager.loadConfigs();
  164. };
  165. Crowi.prototype.setupModels = function() {
  166. const self = this;
  167. return new Promise(((resolve, reject) => {
  168. Object.keys(models).forEach((key) => {
  169. self.model(key, models[key](self));
  170. });
  171. resolve();
  172. }));
  173. };
  174. Crowi.prototype.getIo = function() {
  175. return this.io;
  176. };
  177. Crowi.prototype.scanRuntimeVersions = function() {
  178. const self = this;
  179. const check = require('check-node-version');
  180. return new Promise((resolve, reject) => {
  181. check((err, result) => {
  182. if (err) {
  183. reject(err);
  184. }
  185. self.runtimeVersions = result;
  186. resolve();
  187. });
  188. });
  189. };
  190. Crowi.prototype.getSearcher = function() {
  191. return this.searcher;
  192. };
  193. Crowi.prototype.getMailer = function() {
  194. return this.mailer;
  195. };
  196. Crowi.prototype.getInterceptorManager = function() {
  197. return this.interceptorManager;
  198. };
  199. Crowi.prototype.getGlobalNotificationService = function() {
  200. return this.globalNotificationService;
  201. };
  202. Crowi.prototype.getRestQiitaAPIService = function() {
  203. return this.restQiitaAPIService;
  204. };
  205. Crowi.prototype.setupPassport = function() {
  206. debug('Passport is enabled');
  207. // initialize service
  208. const PassportService = require('../service/passport');
  209. if (this.passportService == null) {
  210. this.passportService = new PassportService(this);
  211. }
  212. this.passportService.setupSerializer();
  213. // setup strategies
  214. this.passportService.setupLocalStrategy();
  215. try {
  216. this.passportService.setupLdapStrategy();
  217. this.passportService.setupGoogleStrategy();
  218. this.passportService.setupGitHubStrategy();
  219. this.passportService.setupTwitterStrategy();
  220. this.passportService.setupOidcStrategy();
  221. this.passportService.setupSamlStrategy();
  222. }
  223. catch (err) {
  224. logger.error(err);
  225. }
  226. return Promise.resolve();
  227. };
  228. Crowi.prototype.setupSearcher = function() {
  229. const self = this;
  230. const searcherUri = this.env.ELASTICSEARCH_URI
  231. || this.env.BONSAI_URL
  232. || null;
  233. return new Promise(((resolve, reject) => {
  234. if (searcherUri) {
  235. try {
  236. self.searcher = new (require(path.join(self.libDir, 'util', 'search')))(self, searcherUri);
  237. }
  238. catch (e) {
  239. logger.error('Error on setup searcher', e);
  240. self.searcher = null;
  241. }
  242. }
  243. resolve();
  244. }));
  245. };
  246. Crowi.prototype.setupMailer = function() {
  247. const self = this;
  248. return new Promise(((resolve, reject) => {
  249. self.mailer = require('../util/mailer')(self);
  250. resolve();
  251. }));
  252. };
  253. Crowi.prototype.setupSlack = function() {
  254. const self = this;
  255. return new Promise(((resolve, reject) => {
  256. if (this.slackNotificationService.hasSlackConfig()) {
  257. self.slack = require('../util/slack')(self);
  258. }
  259. resolve();
  260. }));
  261. };
  262. Crowi.prototype.setupCsrf = function() {
  263. const Tokens = require('csrf');
  264. this.tokens = new Tokens();
  265. return Promise.resolve();
  266. };
  267. Crowi.prototype.getTokens = function() {
  268. return this.tokens;
  269. };
  270. Crowi.prototype.start = async function() {
  271. // init CrowiDev
  272. if (this.node_env === 'development') {
  273. const CrowiDev = require('./dev');
  274. this.crowiDev = new CrowiDev(this);
  275. this.crowiDev.init();
  276. }
  277. await this.init();
  278. const express = await this.buildServer();
  279. const server = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  280. // listen
  281. const serverListening = server.listen(this.port, () => {
  282. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  283. if (this.node_env === 'development') {
  284. this.crowiDev.setupExpressAfterListening(express);
  285. }
  286. });
  287. // setup WebSocket
  288. const io = require('socket.io')(serverListening);
  289. io.sockets.on('connection', (socket) => {
  290. });
  291. this.io = io;
  292. // setup Express Routes
  293. this.setupRoutesAtLast(express);
  294. return serverListening;
  295. };
  296. Crowi.prototype.buildServer = function() {
  297. const express = require('express')();
  298. const env = this.node_env;
  299. require('./express-init')(this, express);
  300. // import plugins
  301. const isEnabledPlugins = this.configManager.getConfig('crowi', 'plugin:isEnabledPlugins');
  302. if (isEnabledPlugins) {
  303. debug('Plugins are enabled');
  304. const PluginService = require('../plugins/plugin.service');
  305. const pluginService = new PluginService(this, express);
  306. pluginService.autoDetectAndLoadPlugins();
  307. if (env === 'development') {
  308. this.crowiDev.loadPlugins(express);
  309. }
  310. }
  311. // use bunyan
  312. if (env === 'production') {
  313. const expressBunyanLogger = require('express-bunyan-logger');
  314. const logger = require('@alias/logger')('express');
  315. express.use(expressBunyanLogger({
  316. logger,
  317. excludes: ['*'],
  318. }));
  319. }
  320. // use morgan
  321. else {
  322. const morgan = require('morgan');
  323. express.use(morgan('dev'));
  324. }
  325. return Promise.resolve(express);
  326. };
  327. /**
  328. * setup Express Routes
  329. * !! this must be at last because it includes '/*' route !!
  330. */
  331. Crowi.prototype.setupRoutesAtLast = function(app) {
  332. require('../routes')(this, app);
  333. };
  334. /**
  335. * require API for plugins
  336. *
  337. * @param {string} modulePath relative path from /lib/crowi/index.js
  338. * @return {module}
  339. *
  340. * @memberof Crowi
  341. */
  342. Crowi.prototype.require = function(modulePath) {
  343. return require(modulePath);
  344. };
  345. /**
  346. * setup GlobalNotificationService
  347. */
  348. Crowi.prototype.setUpGlobalNotification = function() {
  349. const GlobalNotificationService = require('../service/global-notification');
  350. if (this.globalNotificationService == null) {
  351. this.globalNotificationService = new GlobalNotificationService(this);
  352. }
  353. };
  354. /**
  355. * setup SlackNotificationService
  356. */
  357. Crowi.prototype.setUpSlacklNotification = function() {
  358. const SlackNotificationService = require('../service/slack-notification');
  359. if (this.slackNotificationService == null) {
  360. this.slackNotificationService = new SlackNotificationService(this.configManager);
  361. }
  362. };
  363. /**
  364. * setup XssService
  365. */
  366. Crowi.prototype.setUpXss = function() {
  367. const XssService = require('../service/xss');
  368. if (this.xssService == null) {
  369. this.xssService = new XssService(this.configManager);
  370. }
  371. };
  372. /**
  373. * setup AclService
  374. */
  375. Crowi.prototype.setUpAcl = function() {
  376. const AclService = require('../service/acl');
  377. if (this.aclService == null) {
  378. this.aclService = new AclService(this.configManager);
  379. }
  380. };
  381. /**
  382. * setup CustomizeService
  383. */
  384. Crowi.prototype.setUpCustomize = function() {
  385. const CustomizeService = require('../service/customize');
  386. if (this.customizeService == null) {
  387. this.customizeService = new CustomizeService(this.configManager, this.appService, this.xssService);
  388. this.customizeService.initCustomCss();
  389. this.customizeService.initCustomTitle();
  390. }
  391. };
  392. /**
  393. * setup AppService
  394. */
  395. Crowi.prototype.setUpApp = function() {
  396. const AppService = require('../service/app');
  397. if (this.appService == null) {
  398. this.appService = new AppService(this.configManager);
  399. }
  400. };
  401. /**
  402. * setup FileUploadService
  403. */
  404. Crowi.prototype.setUpFileUpload = function() {
  405. if (this.fileUploadService == null) {
  406. this.fileUploadService = require('../service/file-uploader')(this);
  407. }
  408. };
  409. /**
  410. * setup RestQiitaAPIService
  411. */
  412. Crowi.prototype.setUpRestQiitaAPI = function() {
  413. const RestQiitaAPIService = require('../service/rest-qiita-API');
  414. if (this.restQiitaAPIService == null) {
  415. this.restQiitaAPIService = new RestQiitaAPIService(this);
  416. }
  417. };
  418. module.exports = Crowi;