index.js 16 KB

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