index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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 initMiddlewares = require('../middlewares');
  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.restQiitaAPIService = null;
  33. this.cdnResourcesService = new CdnResourcesService();
  34. this.interceptorManager = new InterceptorManager();
  35. this.xss = new Xss();
  36. this.tokens = null;
  37. this.models = {};
  38. this.middlewares = {};
  39. this.env = process.env;
  40. this.node_env = this.env.NODE_ENV || 'development';
  41. this.port = this.env.PORT || 3000;
  42. this.events = {
  43. user: new (require(`${self.eventsDir}user`))(this),
  44. page: new (require(`${self.eventsDir}page`))(this),
  45. search: new (require(`${self.eventsDir}search`))(this),
  46. bookmark: new (require(`${self.eventsDir}bookmark`))(this),
  47. tag: new (require(`${self.eventsDir}tag`))(this),
  48. };
  49. }
  50. function getMongoUrl(env) {
  51. return env.MONGOLAB_URI // for B.C.
  52. || env.MONGODB_URI // MONGOLAB changes their env name
  53. || env.MONGOHQ_URL
  54. || env.MONGO_URI
  55. || ((process.env.NODE_ENV === 'test') ? 'mongodb://localhost/growi_test' : 'mongodb://localhost/growi');
  56. }
  57. Crowi.prototype.init = async function() {
  58. await this.setupDatabase();
  59. await this.setupModels();
  60. await this.setupMiddlewares();
  61. await this.setupSessionConfig();
  62. await this.setupAppConfig();
  63. await this.setupConfigManager();
  64. await Promise.all([
  65. this.scanRuntimeVersions(),
  66. this.setupPassport(),
  67. this.setupSearcher(),
  68. this.setupMailer(),
  69. this.setupSlack(),
  70. this.setupCsrf(),
  71. this.setUpGlobalNotification(),
  72. this.setUpRestQiitaAPI(),
  73. ]);
  74. };
  75. Crowi.prototype.isPageId = function(pageId) {
  76. if (!pageId) {
  77. return false;
  78. }
  79. if (typeof pageId === 'string' && pageId.match(/^[\da-f]{24}$/)) {
  80. return true;
  81. }
  82. return false;
  83. };
  84. Crowi.prototype.setConfig = function(config) {
  85. this.config = config;
  86. };
  87. Crowi.prototype.getConfig = function() {
  88. return this.config;
  89. };
  90. Crowi.prototype.getEnv = function() {
  91. return this.env;
  92. };
  93. // getter/setter of model instance
  94. //
  95. Crowi.prototype.model = function(name, model) {
  96. if (model != null) {
  97. this.models[name] = model;
  98. }
  99. return this.models[name];
  100. };
  101. // getter/setter of event instance
  102. Crowi.prototype.event = function(name, event) {
  103. if (event) {
  104. this.events[name] = event;
  105. }
  106. return this.events[name];
  107. };
  108. Crowi.prototype.setupDatabase = function() {
  109. // mongoUri = mongodb://user:password@host/dbname
  110. mongoose.Promise = global.Promise;
  111. const mongoUri = getMongoUrl(this.env);
  112. return mongoose.connect(mongoUri, { useNewUrlParser: true });
  113. };
  114. Crowi.prototype.setupSessionConfig = function() {
  115. const self = this;
  116. const session = require('express-session');
  117. const sessionAge = (1000 * 3600 * 24 * 30);
  118. const redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URI || this.env.REDIS_URL || null;
  119. const mongoUrl = getMongoUrl(this.env);
  120. let sessionConfig;
  121. return new Promise(((resolve, reject) => {
  122. sessionConfig = {
  123. rolling: true,
  124. secret: self.env.SECRET_TOKEN || 'this is default session secret',
  125. resave: false,
  126. saveUninitialized: true,
  127. cookie: {
  128. maxAge: sessionAge,
  129. },
  130. };
  131. if (self.env.SESSION_NAME) {
  132. sessionConfig.name = self.env.SESSION_NAME;
  133. }
  134. // use Redis for session store
  135. if (redisUrl) {
  136. const RedisStore = require('connect-redis')(session);
  137. sessionConfig.store = new RedisStore({ url: redisUrl });
  138. }
  139. // use MongoDB for session store
  140. else {
  141. const MongoStore = require('connect-mongo')(session);
  142. sessionConfig.store = new MongoStore({ url: mongoUrl });
  143. }
  144. self.sessionConfig = sessionConfig;
  145. resolve();
  146. }));
  147. };
  148. Crowi.prototype.setupAppConfig = function() {
  149. return new Promise((resolve, reject) => {
  150. this.model('Config', require('../models/config')(this));
  151. const Config = this.model('Config');
  152. Config.loadAllConfig((err, doc) => {
  153. if (err) {
  154. return reject();
  155. }
  156. this.setConfig(doc);
  157. return resolve();
  158. });
  159. });
  160. };
  161. Crowi.prototype.setupConfigManager = async function() {
  162. const ConfigManager = require('../service/config-manager');
  163. this.configManager = new ConfigManager(this.model('Config'));
  164. return this.configManager.loadConfigs();
  165. };
  166. Crowi.prototype.setupModels = function() {
  167. const self = this;
  168. return new Promise(((resolve, reject) => {
  169. Object.keys(models).forEach((key) => {
  170. self.model(key, models[key](self));
  171. });
  172. resolve();
  173. }));
  174. };
  175. Crowi.prototype.setupMiddlewares = async function() {
  176. // const self = this;
  177. this.middlewares = await initMiddlewares(this);
  178. };
  179. Crowi.prototype.getIo = function() {
  180. return this.io;
  181. };
  182. Crowi.prototype.scanRuntimeVersions = function() {
  183. const self = this;
  184. const check = require('check-node-version');
  185. return new Promise((resolve, reject) => {
  186. check((err, result) => {
  187. if (err) {
  188. reject(err);
  189. }
  190. self.runtimeVersions = result;
  191. resolve();
  192. });
  193. });
  194. };
  195. Crowi.prototype.getSearcher = function() {
  196. return this.searcher;
  197. };
  198. Crowi.prototype.getMailer = function() {
  199. return this.mailer;
  200. };
  201. Crowi.prototype.getInterceptorManager = function() {
  202. return this.interceptorManager;
  203. };
  204. Crowi.prototype.getGlobalNotificationService = function() {
  205. return this.globalNotificationService;
  206. };
  207. Crowi.prototype.getRestQiitaAPIService = function() {
  208. return this.restQiitaAPIService;
  209. };
  210. Crowi.prototype.setupPassport = function() {
  211. const config = this.getConfig();
  212. const Config = this.model('Config');
  213. if (!Config.isEnabledPassport(config)) {
  214. // disabled
  215. return;
  216. }
  217. debug('Passport is enabled');
  218. // initialize service
  219. const PassportService = require('../service/passport');
  220. if (this.passportService == null) {
  221. this.passportService = new PassportService(this);
  222. }
  223. this.passportService.setupSerializer();
  224. // setup strategies
  225. this.passportService.setupLocalStrategy();
  226. try {
  227. this.passportService.setupLdapStrategy();
  228. this.passportService.setupGoogleStrategy();
  229. this.passportService.setupGitHubStrategy();
  230. this.passportService.setupTwitterStrategy();
  231. this.passportService.setupSamlStrategy();
  232. }
  233. catch (err) {
  234. logger.error(err);
  235. }
  236. return Promise.resolve();
  237. };
  238. Crowi.prototype.setupSearcher = function() {
  239. const self = this;
  240. const searcherUri = this.env.ELASTICSEARCH_URI
  241. || this.env.BONSAI_URL
  242. || null;
  243. return new Promise(((resolve, reject) => {
  244. if (searcherUri) {
  245. try {
  246. self.searcher = new (require(path.join(self.libDir, 'util', 'search')))(self, searcherUri);
  247. }
  248. catch (e) {
  249. logger.error('Error on setup searcher', e);
  250. self.searcher = null;
  251. }
  252. }
  253. resolve();
  254. }));
  255. };
  256. Crowi.prototype.setupMailer = function() {
  257. const self = this;
  258. return new Promise(((resolve, reject) => {
  259. self.mailer = require('../util/mailer')(self);
  260. resolve();
  261. }));
  262. };
  263. Crowi.prototype.setupSlack = function() {
  264. const self = this;
  265. const config = this.getConfig();
  266. const Config = this.model('Config');
  267. return new Promise(((resolve, reject) => {
  268. if (Config.hasSlackConfig(config)) {
  269. self.slack = require('../util/slack')(self);
  270. }
  271. resolve();
  272. }));
  273. };
  274. Crowi.prototype.setupCsrf = function() {
  275. const Tokens = require('csrf');
  276. this.tokens = new Tokens();
  277. return Promise.resolve();
  278. };
  279. Crowi.prototype.getTokens = function() {
  280. return this.tokens;
  281. };
  282. Crowi.prototype.start = async function() {
  283. // init CrowiDev
  284. if (this.node_env === 'development') {
  285. const CrowiDev = require('./dev');
  286. this.crowiDev = new CrowiDev(this);
  287. this.crowiDev.init();
  288. }
  289. await this.init();
  290. const express = await this.buildServer();
  291. const server = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  292. // listen
  293. const serverListening = server.listen(this.port, () => {
  294. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  295. if (this.node_env === 'development') {
  296. this.crowiDev.setupExpressAfterListening(express);
  297. }
  298. });
  299. // setup WebSocket
  300. const io = require('socket.io')(serverListening);
  301. io.sockets.on('connection', (socket) => {
  302. });
  303. this.io = io;
  304. // setup Express Routes
  305. this.setupRoutesAtLast(express);
  306. return serverListening;
  307. };
  308. Crowi.prototype.buildServer = function() {
  309. const express = require('express')();
  310. const env = this.node_env;
  311. require('./express-init')(this, express);
  312. // import plugins
  313. const Config = this.model('Config');
  314. const isEnabledPlugins = Config.isEnabledPlugins(this.config);
  315. if (isEnabledPlugins) {
  316. debug('Plugins are enabled');
  317. const PluginService = require('../plugins/plugin.service');
  318. const pluginService = new PluginService(this, express);
  319. pluginService.autoDetectAndLoadPlugins();
  320. if (env === 'development') {
  321. this.crowiDev.loadPlugins(express);
  322. }
  323. }
  324. // use bunyan
  325. if (env === 'production') {
  326. const expressBunyanLogger = require('express-bunyan-logger');
  327. const logger = require('@alias/logger')('express');
  328. express.use(expressBunyanLogger({
  329. logger,
  330. excludes: ['*'],
  331. }));
  332. }
  333. // use morgan
  334. else {
  335. const morgan = require('morgan');
  336. express.use(morgan('dev'));
  337. }
  338. return Promise.resolve(express);
  339. };
  340. /**
  341. * setup Express Routes
  342. * !! this must be at last because it includes '/*' route !!
  343. */
  344. Crowi.prototype.setupRoutesAtLast = function(app) {
  345. require('../routes')(this, app);
  346. };
  347. /**
  348. * require API for plugins
  349. *
  350. * @param {string} modulePath relative path from /lib/crowi/index.js
  351. * @return {module}
  352. *
  353. * @memberof Crowi
  354. */
  355. Crowi.prototype.require = function(modulePath) {
  356. return require(modulePath);
  357. };
  358. /**
  359. * setup GlobalNotificationService
  360. */
  361. Crowi.prototype.setUpGlobalNotification = function() {
  362. const GlobalNotificationService = require('../service/global-notification');
  363. if (this.globalNotificationService == null) {
  364. this.globalNotificationService = new GlobalNotificationService(this);
  365. }
  366. };
  367. /**
  368. * setup RestQiitaAPIService
  369. */
  370. Crowi.prototype.setUpRestQiitaAPI = function() {
  371. const RestQiitaAPIService = require('../service/rest-qiita-API');
  372. if (this.restQiitaAPIService == null) {
  373. this.restQiitaAPIService = new RestQiitaAPIService(this);
  374. }
  375. };
  376. module.exports = Crowi;