index.js 13 KB

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