index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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.setupOidcStrategy();
  225. this.passportService.setupSamlStrategy();
  226. this.passportService.setupBasicStrategy();
  227. }
  228. catch (err) {
  229. logger.error(err);
  230. }
  231. return Promise.resolve();
  232. };
  233. Crowi.prototype.setupSearcher = function() {
  234. const self = this;
  235. const searcherUri = this.env.ELASTICSEARCH_URI
  236. || this.env.BONSAI_URL
  237. || null;
  238. return new Promise(((resolve, reject) => {
  239. if (searcherUri) {
  240. try {
  241. self.searcher = new (require(path.join(self.libDir, 'util', 'search')))(self, searcherUri);
  242. }
  243. catch (e) {
  244. logger.error('Error on setup searcher', e);
  245. self.searcher = null;
  246. }
  247. }
  248. resolve();
  249. }));
  250. };
  251. Crowi.prototype.setupMailer = function() {
  252. const self = this;
  253. return new Promise(((resolve, reject) => {
  254. self.mailer = require('../util/mailer')(self);
  255. resolve();
  256. }));
  257. };
  258. Crowi.prototype.setupSlack = function() {
  259. const self = this;
  260. const config = this.getConfig();
  261. const Config = this.model('Config');
  262. return new Promise(((resolve, reject) => {
  263. if (Config.hasSlackConfig(config)) {
  264. self.slack = require('../util/slack')(self);
  265. }
  266. resolve();
  267. }));
  268. };
  269. Crowi.prototype.setupCsrf = function() {
  270. const Tokens = require('csrf');
  271. this.tokens = new Tokens();
  272. return Promise.resolve();
  273. };
  274. Crowi.prototype.getTokens = function() {
  275. return this.tokens;
  276. };
  277. Crowi.prototype.start = async function() {
  278. // init CrowiDev
  279. if (this.node_env === 'development') {
  280. const CrowiDev = require('./dev');
  281. this.crowiDev = new CrowiDev(this);
  282. this.crowiDev.init();
  283. }
  284. await this.init();
  285. const express = await this.buildServer();
  286. const server = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  287. // listen
  288. const serverListening = server.listen(this.port, () => {
  289. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  290. if (this.node_env === 'development') {
  291. this.crowiDev.setupExpressAfterListening(express);
  292. }
  293. });
  294. // setup WebSocket
  295. const io = require('socket.io')(serverListening);
  296. io.sockets.on('connection', (socket) => {
  297. });
  298. this.io = io;
  299. // setup Express Routes
  300. this.setupRoutesAtLast(express);
  301. return serverListening;
  302. };
  303. Crowi.prototype.buildServer = function() {
  304. const express = require('express')();
  305. const env = this.node_env;
  306. require('./express-init')(this, express);
  307. // import plugins
  308. const Config = this.model('Config');
  309. const isEnabledPlugins = Config.isEnabledPlugins(this.config);
  310. if (isEnabledPlugins) {
  311. debug('Plugins are enabled');
  312. const PluginService = require('../plugins/plugin.service');
  313. const pluginService = new PluginService(this, express);
  314. pluginService.autoDetectAndLoadPlugins();
  315. if (env === 'development') {
  316. this.crowiDev.loadPlugins(express);
  317. }
  318. }
  319. // use bunyan
  320. if (env === 'production') {
  321. const expressBunyanLogger = require('express-bunyan-logger');
  322. const logger = require('@alias/logger')('express');
  323. express.use(expressBunyanLogger({
  324. logger,
  325. excludes: ['*'],
  326. }));
  327. }
  328. // use morgan
  329. else {
  330. const morgan = require('morgan');
  331. express.use(morgan('dev'));
  332. }
  333. return Promise.resolve(express);
  334. };
  335. /**
  336. * setup Express Routes
  337. * !! this must be at last because it includes '/*' route !!
  338. */
  339. Crowi.prototype.setupRoutesAtLast = function(app) {
  340. require('../routes')(this, app);
  341. };
  342. /**
  343. * require API for plugins
  344. *
  345. * @param {string} modulePath relative path from /lib/crowi/index.js
  346. * @return {module}
  347. *
  348. * @memberof Crowi
  349. */
  350. Crowi.prototype.require = function(modulePath) {
  351. return require(modulePath);
  352. };
  353. /**
  354. * setup GlobalNotificationService
  355. */
  356. Crowi.prototype.setUpGlobalNotification = function() {
  357. const GlobalNotificationService = require('../service/global-notification');
  358. if (this.globalNotificationService == null) {
  359. this.globalNotificationService = new GlobalNotificationService(this);
  360. }
  361. };
  362. /**
  363. * setup RestQiitaAPIService
  364. */
  365. Crowi.prototype.setUpRestQiitaAPI = function() {
  366. const RestQiitaAPIService = require('../service/rest-qiita-API');
  367. if (this.restQiitaAPIService == null) {
  368. this.restQiitaAPIService = new RestQiitaAPIService(this);
  369. }
  370. };
  371. module.exports = Crowi;