index.js 17 KB

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