index.js 15 KB

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