web.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. const autoload = require('auto-load')
  2. const bodyParser = require('body-parser')
  3. const compression = require('compression')
  4. const cookieParser = require('cookie-parser')
  5. const cors = require('cors')
  6. const express = require('express')
  7. const session = require('express-session')
  8. const KnexSessionStore = require('connect-session-knex')(session)
  9. const favicon = require('serve-favicon')
  10. const path = require('path')
  11. const _ = require('lodash')
  12. module.exports = async () => {
  13. // ----------------------------------------
  14. // Load core modules
  15. // ----------------------------------------
  16. WIKI.auth = require('./core/auth').init()
  17. WIKI.mail = require('./core/mail').init()
  18. WIKI.system = require('./core/system').init()
  19. // ----------------------------------------
  20. // Load middlewares
  21. // ----------------------------------------
  22. const mw = autoload(path.join(WIKI.SERVERPATH, '/middlewares'))
  23. const ctrl = autoload(path.join(WIKI.SERVERPATH, '/controllers'))
  24. // ----------------------------------------
  25. // Define Express App
  26. // ----------------------------------------
  27. const app = express()
  28. WIKI.app = app
  29. app.use(compression())
  30. // ----------------------------------------
  31. // Initialize HTTP/HTTPS Server
  32. // ----------------------------------------
  33. const useHTTPS = WIKI.config.ssl.enabled === true || WIKI.config.ssl.enabled === 'true' || WIKI.config.ssl.enabled === 1 || WIKI.config.ssl.enabled === '1'
  34. await WIKI.servers.initHTTP()
  35. if (useHTTPS) {
  36. await WIKI.servers.initHTTPS()
  37. }
  38. await WIKI.servers.initWebSocket()
  39. // ----------------------------------------
  40. // Attach WebSocket Server
  41. // ----------------------------------------
  42. ctrl.ws()
  43. // ----------------------------------------
  44. // Security
  45. // ----------------------------------------
  46. app.use(mw.security)
  47. app.use(cors({ origin: false }))
  48. app.options('*', cors({ origin: false }))
  49. if (WIKI.config.security.securityTrustProxy) {
  50. app.enable('trust proxy')
  51. }
  52. // ----------------------------------------
  53. // Public Assets
  54. // ----------------------------------------
  55. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  56. app.use('/_assets', express.static(path.join(WIKI.ROOTPATH, 'assets/_assets'), {
  57. index: false,
  58. maxAge: '7d'
  59. }))
  60. app.use('/_assets-legacy/svg/twemoji', async (req, res, next) => {
  61. try {
  62. WIKI.asar.serve('twemoji', req, res, next)
  63. } catch (err) {
  64. res.sendStatus(404)
  65. }
  66. })
  67. app.use('/_assets-legacy', express.static(path.join(WIKI.ROOTPATH, 'assets-legacy'), {
  68. index: false,
  69. maxAge: '7d'
  70. }))
  71. // ----------------------------------------
  72. // SSL Handlers
  73. // ----------------------------------------
  74. app.use('/', ctrl.ssl)
  75. // ----------------------------------------
  76. // Passport Authentication
  77. // ----------------------------------------
  78. app.use(cookieParser())
  79. app.use(session({
  80. secret: WIKI.config.auth.secret,
  81. resave: false,
  82. saveUninitialized: false,
  83. store: new KnexSessionStore({
  84. knex: WIKI.db.knex
  85. })
  86. }))
  87. app.use(WIKI.auth.passport.initialize())
  88. app.use(WIKI.auth.authenticate)
  89. // ----------------------------------------
  90. // GraphQL Server
  91. // ----------------------------------------
  92. app.use(bodyParser.json({ limit: WIKI.config.bodyParserLimit || '1mb' }))
  93. await WIKI.servers.startGraphQL()
  94. // ----------------------------------------
  95. // SEO
  96. // ----------------------------------------
  97. app.use(mw.seo)
  98. // ----------------------------------------
  99. // View Engine Setup
  100. // ----------------------------------------
  101. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  102. app.set('view engine', 'pug')
  103. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  104. // ----------------------------------------
  105. // View accessible data
  106. // ----------------------------------------
  107. app.locals.siteConfig = {}
  108. app.locals.analyticsCode = {}
  109. app.locals.basedir = WIKI.ROOTPATH
  110. app.locals.config = WIKI.config
  111. app.locals.pageMeta = {
  112. title: '',
  113. description: WIKI.config.description,
  114. image: '',
  115. url: '/'
  116. }
  117. app.locals.devMode = WIKI.devMode
  118. // ----------------------------------------
  119. // HMR (Dev Mode Only)
  120. // ----------------------------------------
  121. if (global.DEV) {
  122. app.use(global.WP_DEV.devMiddleware)
  123. app.use(global.WP_DEV.hotMiddleware)
  124. }
  125. // ----------------------------------------
  126. // Routing
  127. // ----------------------------------------
  128. app.use(async (req, res, next) => {
  129. const currentSite = await WIKI.db.sites.getSiteByHostname({ hostname: req.hostname })
  130. if (!currentSite) {
  131. return res.status(404).send('Site Not Found')
  132. }
  133. res.locals.siteConfig = {
  134. id: currentSite.id,
  135. title: currentSite.config.title,
  136. darkMode: currentSite.config.theme.dark,
  137. lang: currentSite.config.locale,
  138. rtl: false, // TODO: handle RTL
  139. company: currentSite.config.company,
  140. contentLicense: currentSite.config.contentLicense
  141. }
  142. res.locals.langs = await WIKI.db.locales.getNavLocales({ cache: true })
  143. res.locals.analyticsCode = await WIKI.db.analytics.getCode({ cache: true })
  144. next()
  145. })
  146. app.use('/', ctrl.auth)
  147. app.use('/', ctrl.upload)
  148. app.use('/', ctrl.common)
  149. // ----------------------------------------
  150. // Error handling
  151. // ----------------------------------------
  152. app.use((req, res, next) => {
  153. const err = new Error('Not Found')
  154. err.status = 404
  155. next(err)
  156. })
  157. app.use((err, req, res, next) => {
  158. if (req.path === '/_graphql') {
  159. res.status(err.status || 500).json({
  160. data: {},
  161. errors: [{
  162. message: err.message,
  163. path: []
  164. }]
  165. })
  166. } else {
  167. res.status(err.status || 500)
  168. _.set(res.locals, 'pageMeta.title', 'Error')
  169. res.render('error', {
  170. message: err.message,
  171. error: WIKI.IS_DEBUG ? err : {}
  172. })
  173. }
  174. })
  175. // ----------------------------------------
  176. // Start HTTP Server(s)
  177. // ----------------------------------------
  178. await WIKI.servers.startHTTP()
  179. if (useHTTPS) {
  180. await WIKI.servers.startHTTPS()
  181. }
  182. return true
  183. }