index.js 15 KB

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