index.js 11 KB

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