index.js 14 KB

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