index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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 { getMongoUri, mongoOptions } = require('@commons/util/mongoose-utils');
  8. const path = require('path');
  9. const mongoose = require('mongoose');
  10. const models = require('../models');
  11. const PluginService = require('../plugins/plugin.service');
  12. const sep = path.sep;
  13. function Crowi(rootdir) {
  14. const self = this;
  15. this.version = pkg.version;
  16. this.runtimeVersions = undefined; // initialized by scanRuntimeVersions()
  17. this.rootDir = rootdir;
  18. this.pluginDir = path.join(this.rootDir, 'node_modules') + sep;
  19. this.publicDir = path.join(this.rootDir, 'public') + sep;
  20. this.libDir = path.join(this.rootDir, 'src/server') + sep;
  21. this.eventsDir = path.join(this.libDir, 'events') + sep;
  22. this.viewsDir = path.join(this.libDir, 'views') + sep;
  23. this.resourceDir = path.join(this.rootDir, 'resource') + sep;
  24. this.localeDir = path.join(this.resourceDir, 'locales') + sep;
  25. this.tmpDir = path.join(this.rootDir, 'tmp') + sep;
  26. this.cacheDir = path.join(this.tmpDir, 'cache');
  27. this.express = null;
  28. this.config = {};
  29. this.configManager = null;
  30. this.s2sMessagingService = null;
  31. this.mailService = null;
  32. this.passportService = null;
  33. this.globalNotificationService = null;
  34. this.slackNotificationService = null;
  35. this.xssService = null;
  36. this.aclService = null;
  37. this.appService = null;
  38. this.fileUploadService = null;
  39. this.restQiitaAPIService = null;
  40. this.growiBridgeService = null;
  41. this.exportService = null;
  42. this.importService = null;
  43. this.searchService = null;
  44. this.socketIoService = null;
  45. this.pageService = null;
  46. this.syncPageStatusService = null;
  47. this.cdnResourcesService = new CdnResourcesService();
  48. this.interceptorManager = new InterceptorManager();
  49. this.xss = new Xss();
  50. this.tokens = null;
  51. this.models = {};
  52. this.env = process.env;
  53. this.node_env = this.env.NODE_ENV || 'development';
  54. this.port = this.env.PORT || 3000;
  55. this.events = {
  56. user: new (require(`${self.eventsDir}user`))(this),
  57. page: new (require(`${self.eventsDir}page`))(this),
  58. bookmark: new (require(`${self.eventsDir}bookmark`))(this),
  59. tag: new (require(`${self.eventsDir}tag`))(this),
  60. admin: new (require(`${self.eventsDir}admin`))(this),
  61. };
  62. }
  63. Crowi.prototype.init = async function() {
  64. await this.setupDatabase();
  65. await this.setupModels();
  66. await this.setupSessionConfig();
  67. await this.setupConfigManager();
  68. // setup messaging services
  69. await this.setupS2sMessagingService();
  70. await this.setupSocketIoService();
  71. // customizeService depends on AppService and XssService
  72. // passportService depends on appService
  73. // slack depends on setUpSlacklNotification
  74. // export and import depends on setUpGrowiBridge
  75. await Promise.all([
  76. this.setUpApp(),
  77. this.setUpXss(),
  78. this.setUpSlacklNotification(),
  79. this.setUpGrowiBridge(),
  80. ]);
  81. await Promise.all([
  82. this.scanRuntimeVersions(),
  83. this.setupPassport(),
  84. this.setupSearcher(),
  85. this.setupMailer(),
  86. this.setupSlack(),
  87. this.setupCsrf(),
  88. this.setUpFileUpload(),
  89. this.setUpFileUploaderSwitchService(),
  90. this.setupAttachmentService(),
  91. this.setUpAcl(),
  92. this.setUpCustomize(),
  93. this.setUpRestQiitaAPI(),
  94. this.setupUserGroup(),
  95. this.setupExport(),
  96. this.setupImport(),
  97. this.setupPageService(),
  98. this.setupSyncPageStatusService(),
  99. ]);
  100. // globalNotification depends on slack and mailer
  101. await Promise.all([
  102. this.setUpGlobalNotification(),
  103. ]);
  104. };
  105. Crowi.prototype.initForTest = async function() {
  106. await this.setupModels();
  107. await this.setupConfigManager();
  108. // // customizeService depends on AppService and XssService
  109. // // passportService depends on appService
  110. // // slack depends on setUpSlacklNotification
  111. await Promise.all([
  112. this.setUpApp(),
  113. this.setUpXss(),
  114. // this.setUpSlacklNotification(),
  115. // this.setUpGrowiBridge(),
  116. ]);
  117. await Promise.all([
  118. // this.scanRuntimeVersions(),
  119. this.setupPassport(),
  120. // this.setupSearcher(),
  121. // this.setupMailer(),
  122. // this.setupSlack(),
  123. // this.setupCsrf(),
  124. // this.setUpFileUpload(),
  125. // this.setupAttachmentService(),
  126. this.setUpAcl(),
  127. // this.setUpCustomize(),
  128. // this.setUpRestQiitaAPI(),
  129. // this.setupUserGroup(),
  130. // this.setupExport(),
  131. // this.setupImport(),
  132. ]);
  133. // globalNotification depends on slack and mailer
  134. // await Promise.all([
  135. // this.setUpGlobalNotification(),
  136. // ]);
  137. };
  138. Crowi.prototype.isPageId = function(pageId) {
  139. if (!pageId) {
  140. return false;
  141. }
  142. if (typeof pageId === 'string' && pageId.match(/^[\da-f]{24}$/)) {
  143. return true;
  144. }
  145. return false;
  146. };
  147. Crowi.prototype.setConfig = function(config) {
  148. this.config = config;
  149. };
  150. Crowi.prototype.getConfig = function() {
  151. return this.config;
  152. };
  153. Crowi.prototype.getEnv = function() {
  154. return this.env;
  155. };
  156. // getter/setter of model instance
  157. //
  158. Crowi.prototype.model = function(name, model) {
  159. if (model != null) {
  160. this.models[name] = model;
  161. }
  162. return this.models[name];
  163. };
  164. // getter/setter of event instance
  165. Crowi.prototype.event = function(name, event) {
  166. if (event) {
  167. this.events[name] = event;
  168. }
  169. return this.events[name];
  170. };
  171. Crowi.prototype.setupDatabase = function() {
  172. mongoose.Promise = global.Promise;
  173. // mongoUri = mongodb://user:password@host/dbname
  174. const mongoUri = getMongoUri();
  175. return mongoose.connect(mongoUri, mongoOptions);
  176. };
  177. Crowi.prototype.setupSessionConfig = async function() {
  178. const session = require('express-session');
  179. const sessionAge = (1000 * 3600 * 24 * 30);
  180. const redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URI || this.env.REDIS_URL || null;
  181. const uid = require('uid-safe').sync;
  182. // generate pre-defined uid for healthcheck
  183. const healthcheckUid = uid(24);
  184. const sessionConfig = {
  185. rolling: true,
  186. secret: this.env.SECRET_TOKEN || 'this is default session secret',
  187. resave: false,
  188. saveUninitialized: true,
  189. cookie: {
  190. maxAge: sessionAge,
  191. },
  192. genid(req) {
  193. // return pre-defined uid when healthcheck
  194. if (req.path === '/_api/v3/healthcheck') {
  195. return healthcheckUid;
  196. }
  197. return uid(24);
  198. },
  199. };
  200. if (this.env.SESSION_NAME) {
  201. sessionConfig.name = this.env.SESSION_NAME;
  202. }
  203. // use Redis for session store
  204. if (redisUrl) {
  205. const redis = require('redis');
  206. const redisClient = redis.createClient({ url: redisUrl });
  207. const RedisStore = require('connect-redis')(session);
  208. sessionConfig.store = new RedisStore({ client: redisClient });
  209. }
  210. // use MongoDB for session store
  211. else {
  212. const MongoStore = require('connect-mongo')(session);
  213. sessionConfig.store = new MongoStore({ mongooseConnection: mongoose.connection });
  214. }
  215. this.sessionConfig = sessionConfig;
  216. };
  217. Crowi.prototype.setupConfigManager = async function() {
  218. const ConfigManager = require('../service/config-manager');
  219. this.configManager = new ConfigManager(this.model('Config'));
  220. return this.configManager.loadConfigs();
  221. };
  222. Crowi.prototype.setupS2sMessagingService = async function() {
  223. const s2sMessagingService = require('../service/s2s-messaging')(this);
  224. if (s2sMessagingService != null) {
  225. s2sMessagingService.subscribe();
  226. this.configManager.setS2sMessagingService(s2sMessagingService);
  227. // add as a message handler
  228. s2sMessagingService.addMessageHandler(this.configManager);
  229. this.s2sMessagingService = s2sMessagingService;
  230. }
  231. };
  232. Crowi.prototype.setupSocketIoService = async function() {
  233. const SocketIoService = require('../service/socket-io');
  234. if (this.socketIoService == null) {
  235. this.socketIoService = new SocketIoService(this);
  236. }
  237. };
  238. Crowi.prototype.setupModels = async function() {
  239. Object.keys(models).forEach((key) => {
  240. return this.model(key, models[key](this));
  241. });
  242. };
  243. Crowi.prototype.scanRuntimeVersions = async function() {
  244. const self = this;
  245. const check = require('check-node-version');
  246. return new Promise((resolve, reject) => {
  247. check((err, result) => {
  248. if (err) {
  249. reject(err);
  250. }
  251. self.runtimeVersions = result;
  252. resolve();
  253. });
  254. });
  255. };
  256. Crowi.prototype.getSlack = function() {
  257. return this.slack;
  258. };
  259. Crowi.prototype.getInterceptorManager = function() {
  260. return this.interceptorManager;
  261. };
  262. Crowi.prototype.getGlobalNotificationService = function() {
  263. return this.globalNotificationService;
  264. };
  265. Crowi.prototype.getRestQiitaAPIService = function() {
  266. return this.restQiitaAPIService;
  267. };
  268. Crowi.prototype.setupPassport = async function() {
  269. debug('Passport is enabled');
  270. // initialize service
  271. const PassportService = require('../service/passport');
  272. if (this.passportService == null) {
  273. this.passportService = new PassportService(this);
  274. }
  275. this.passportService.setupSerializer();
  276. // setup strategies
  277. try {
  278. this.passportService.setupStrategyById('local');
  279. this.passportService.setupStrategyById('ldap');
  280. this.passportService.setupStrategyById('saml');
  281. this.passportService.setupStrategyById('oidc');
  282. this.passportService.setupStrategyById('basic');
  283. this.passportService.setupStrategyById('google');
  284. this.passportService.setupStrategyById('github');
  285. this.passportService.setupStrategyById('twitter');
  286. }
  287. catch (err) {
  288. logger.error(err);
  289. }
  290. // add as a message handler
  291. if (this.s2sMessagingService != null) {
  292. this.s2sMessagingService.addMessageHandler(this.passportService);
  293. }
  294. return Promise.resolve();
  295. };
  296. Crowi.prototype.setupSearcher = async function() {
  297. const SearchService = require('@server/service/search');
  298. this.searchService = new SearchService(this);
  299. };
  300. Crowi.prototype.setupMailer = async function() {
  301. const MailService = require('@server/service/mail');
  302. this.mailService = new MailService(this);
  303. // add as a message handler
  304. if (this.s2sMessagingService != null) {
  305. this.s2sMessagingService.addMessageHandler(this.mailService);
  306. }
  307. };
  308. Crowi.prototype.setupSlack = async function() {
  309. const self = this;
  310. return new Promise(((resolve, reject) => {
  311. self.slack = require('../util/slack')(self);
  312. resolve();
  313. }));
  314. };
  315. Crowi.prototype.setupCsrf = async function() {
  316. const Tokens = require('csrf');
  317. this.tokens = new Tokens();
  318. return Promise.resolve();
  319. };
  320. Crowi.prototype.getTokens = function() {
  321. return this.tokens;
  322. };
  323. Crowi.prototype.start = async function() {
  324. // init CrowiDev
  325. if (this.node_env === 'development') {
  326. const CrowiDev = require('./dev');
  327. this.crowiDev = new CrowiDev(this);
  328. this.crowiDev.init();
  329. }
  330. await this.init();
  331. await this.buildServer();
  332. const { express } = this;
  333. // setup plugins
  334. this.pluginService = new PluginService(this, express);
  335. this.pluginService.autoDetectAndLoadPlugins();
  336. const server = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  337. // listen
  338. const serverListening = server.listen(this.port, () => {
  339. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  340. if (this.node_env === 'development') {
  341. this.crowiDev.setupExpressAfterListening(express);
  342. }
  343. });
  344. this.socketIoService.attachServer(serverListening);
  345. // setup Express Routes
  346. this.setupRoutesAtLast();
  347. return serverListening;
  348. };
  349. Crowi.prototype.buildServer = async function() {
  350. const env = this.node_env;
  351. const express = require('express')();
  352. require('./express-init')(this, express);
  353. // use bunyan
  354. if (env === 'production') {
  355. const expressBunyanLogger = require('express-bunyan-logger');
  356. const logger = require('@alias/logger')('express');
  357. express.use(expressBunyanLogger({
  358. logger,
  359. excludes: ['*'],
  360. }));
  361. }
  362. // use morgan
  363. else {
  364. const morgan = require('morgan');
  365. express.use(morgan('dev'));
  366. }
  367. this.express = express;
  368. };
  369. /**
  370. * setup Express Routes
  371. * !! this must be at last because it includes '/*' route !!
  372. */
  373. Crowi.prototype.setupRoutesAtLast = function() {
  374. require('../routes')(this, this.express);
  375. };
  376. Crowi.prototype.setupAfterInstall = function() {
  377. this.pluginService.autoDetectAndLoadPlugins();
  378. this.setupRoutesAtLast();
  379. };
  380. /**
  381. * require API for plugins
  382. *
  383. * @param {string} modulePath relative path from /lib/crowi/index.js
  384. * @return {module}
  385. *
  386. * @memberof Crowi
  387. */
  388. Crowi.prototype.require = function(modulePath) {
  389. return require(modulePath);
  390. };
  391. /**
  392. * setup GlobalNotificationService
  393. */
  394. Crowi.prototype.setUpGlobalNotification = async function() {
  395. const GlobalNotificationService = require('../service/global-notification');
  396. if (this.globalNotificationService == null) {
  397. this.globalNotificationService = new GlobalNotificationService(this);
  398. }
  399. };
  400. /**
  401. * setup SlackNotificationService
  402. */
  403. Crowi.prototype.setUpSlacklNotification = async function() {
  404. const SlackNotificationService = require('../service/slack-notification');
  405. if (this.slackNotificationService == null) {
  406. this.slackNotificationService = new SlackNotificationService(this.configManager);
  407. }
  408. };
  409. /**
  410. * setup XssService
  411. */
  412. Crowi.prototype.setUpXss = async function() {
  413. const XssService = require('../service/xss');
  414. if (this.xssService == null) {
  415. this.xssService = new XssService(this.configManager);
  416. }
  417. };
  418. /**
  419. * setup AclService
  420. */
  421. Crowi.prototype.setUpAcl = async function() {
  422. const AclService = require('../service/acl');
  423. if (this.aclService == null) {
  424. this.aclService = new AclService(this.configManager);
  425. }
  426. };
  427. /**
  428. * setup CustomizeService
  429. */
  430. Crowi.prototype.setUpCustomize = async function() {
  431. const CustomizeService = require('../service/customize');
  432. if (this.customizeService == null) {
  433. this.customizeService = new CustomizeService(this);
  434. this.customizeService.initCustomCss();
  435. this.customizeService.initCustomTitle();
  436. // add as a message handler
  437. if (this.s2sMessagingService != null) {
  438. this.s2sMessagingService.addMessageHandler(this.customizeService);
  439. }
  440. }
  441. };
  442. /**
  443. * setup AppService
  444. */
  445. Crowi.prototype.setUpApp = async function() {
  446. const AppService = require('../service/app');
  447. if (this.appService == null) {
  448. this.appService = new AppService(this);
  449. // add as a message handler
  450. const isInstalled = this.configManager.getConfig('crowi', 'app:installed');
  451. if (this.s2sMessagingService != null && !isInstalled) {
  452. this.s2sMessagingService.addMessageHandler(this.appService);
  453. }
  454. }
  455. };
  456. /**
  457. * setup FileUploadService
  458. */
  459. Crowi.prototype.setUpFileUpload = async function(isForceUpdate = false) {
  460. if (this.fileUploadService == null || isForceUpdate) {
  461. this.fileUploadService = require('../service/file-uploader')(this);
  462. }
  463. };
  464. /**
  465. * setup FileUploaderSwitchService
  466. */
  467. Crowi.prototype.setUpFileUploaderSwitchService = async function() {
  468. const FileUploaderSwitchService = require('../service/file-uploader-switch');
  469. this.fileUploaderSwitchService = new FileUploaderSwitchService(this);
  470. // add as a message handler
  471. if (this.s2sMessagingService != null) {
  472. this.s2sMessagingService.addMessageHandler(this.fileUploaderSwitchService);
  473. }
  474. };
  475. /**
  476. * setup AttachmentService
  477. */
  478. Crowi.prototype.setupAttachmentService = async function() {
  479. const AttachmentService = require('../service/attachment');
  480. if (this.attachmentService == null) {
  481. this.attachmentService = new AttachmentService(this);
  482. }
  483. };
  484. /**
  485. * setup RestQiitaAPIService
  486. */
  487. Crowi.prototype.setUpRestQiitaAPI = async function() {
  488. const RestQiitaAPIService = require('../service/rest-qiita-API');
  489. if (this.restQiitaAPIService == null) {
  490. this.restQiitaAPIService = new RestQiitaAPIService(this);
  491. }
  492. };
  493. Crowi.prototype.setupUserGroup = async function() {
  494. const UserGroupService = require('../service/user-group');
  495. if (this.userGroupService == null) {
  496. this.userGroupService = new UserGroupService(this);
  497. return this.userGroupService.init();
  498. }
  499. };
  500. Crowi.prototype.setUpGrowiBridge = async function() {
  501. const GrowiBridgeService = require('../service/growi-bridge');
  502. if (this.growiBridgeService == null) {
  503. this.growiBridgeService = new GrowiBridgeService(this);
  504. }
  505. };
  506. Crowi.prototype.setupExport = async function() {
  507. const ExportService = require('../service/export');
  508. if (this.exportService == null) {
  509. this.exportService = new ExportService(this);
  510. }
  511. };
  512. Crowi.prototype.setupImport = async function() {
  513. const ImportService = require('../service/import');
  514. if (this.importService == null) {
  515. this.importService = new ImportService(this);
  516. }
  517. };
  518. Crowi.prototype.setupPageService = async function() {
  519. const PageEventService = require('../service/page');
  520. if (this.pageService == null) {
  521. this.pageService = new PageEventService(this);
  522. }
  523. };
  524. Crowi.prototype.setupSyncPageStatusService = async function() {
  525. const SyncPageStatusService = require('../service/system-events/sync-page-status');
  526. if (this.syncPageStatusService == null) {
  527. this.syncPageStatusService = new SyncPageStatusService(this, this.s2sMessagingService, this.socketIoService);
  528. // add as a message handler
  529. if (this.s2sMessagingService != null) {
  530. this.s2sMessagingService.addMessageHandler(this.syncPageStatusService);
  531. }
  532. }
  533. };
  534. module.exports = Crowi;