master.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 favicon = require('serve-favicon')
  9. const fs = require('fs-extra')
  10. const http = require('http')
  11. const https = require('https')
  12. const path = require('path')
  13. const _ = require('lodash')
  14. const { ApolloServer } = require('apollo-server-express')
  15. /* global WIKI */
  16. module.exports = async () => {
  17. // ----------------------------------------
  18. // Load core modules
  19. // ----------------------------------------
  20. WIKI.auth = require('./core/auth').init()
  21. WIKI.lang = require('./core/localization').init()
  22. WIKI.mail = require('./core/mail').init()
  23. WIKI.system = require('./core/system').init()
  24. // ----------------------------------------
  25. // Load middlewares
  26. // ----------------------------------------
  27. var mw = autoload(path.join(WIKI.SERVERPATH, '/middlewares'))
  28. var ctrl = autoload(path.join(WIKI.SERVERPATH, '/controllers'))
  29. // ----------------------------------------
  30. // Define Express App
  31. // ----------------------------------------
  32. const app = express()
  33. WIKI.app = app
  34. app.use(compression())
  35. // ----------------------------------------
  36. // Security
  37. // ----------------------------------------
  38. app.use(mw.security)
  39. app.use(cors(WIKI.config.cors))
  40. app.options('*', cors(WIKI.config.cors))
  41. if (WIKI.config.trustProxy) {
  42. app.enable('trust proxy')
  43. }
  44. // ----------------------------------------
  45. // Public Assets
  46. // ----------------------------------------
  47. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  48. app.use(express.static(path.join(WIKI.ROOTPATH, 'assets'), {
  49. index: false,
  50. maxAge: '7d'
  51. }))
  52. // ----------------------------------------
  53. // Passport Authentication
  54. // ----------------------------------------
  55. app.use(cookieParser())
  56. app.use(session({
  57. secret: WIKI.config.sessionSecret,
  58. resave: false,
  59. saveUninitialized: false
  60. }))
  61. app.use(WIKI.auth.passport.initialize())
  62. app.use(WIKI.auth.authenticate)
  63. // ----------------------------------------
  64. // SEO
  65. // ----------------------------------------
  66. app.use(mw.seo)
  67. // ----------------------------------------
  68. // View Engine Setup
  69. // ----------------------------------------
  70. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  71. app.set('view engine', 'pug')
  72. app.use(bodyParser.json({ limit: '1mb' }))
  73. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  74. // ----------------------------------------
  75. // Localization
  76. // ----------------------------------------
  77. WIKI.lang.attachMiddleware(app)
  78. // ----------------------------------------
  79. // View accessible data
  80. // ----------------------------------------
  81. app.locals.basedir = WIKI.ROOTPATH
  82. app.locals._ = require('lodash')
  83. app.locals.moment = require('moment')
  84. app.locals.moment.locale(WIKI.config.lang.code)
  85. app.locals.config = WIKI.config
  86. app.locals.pageMeta = {
  87. title: '',
  88. description: WIKI.config.description,
  89. image: '',
  90. url: '/'
  91. }
  92. // ----------------------------------------
  93. // HMR (Dev Mode Only)
  94. // ----------------------------------------
  95. if (global.DEV) {
  96. app.use(global.WP_DEV.devMiddleware)
  97. app.use(global.WP_DEV.hotMiddleware)
  98. }
  99. // ----------------------------------------
  100. // Apollo Server (GraphQL)
  101. // ----------------------------------------
  102. const graphqlSchema = require('./graph')
  103. const apolloServer = new ApolloServer({
  104. ...graphqlSchema,
  105. context: ({ req, res }) => ({ req, res }),
  106. subscriptions: {
  107. onConnect: (connectionParams, webSocket) => {
  108. },
  109. path: '/graphql-subscriptions'
  110. }
  111. })
  112. app.use('/graphql', mw.upload)
  113. apolloServer.applyMiddleware({ app })
  114. // ----------------------------------------
  115. // Routing
  116. // ----------------------------------------
  117. app.use('/', ctrl.auth)
  118. app.use('/', ctrl.common)
  119. // ----------------------------------------
  120. // Error handling
  121. // ----------------------------------------
  122. app.use((req, res, next) => {
  123. var err = new Error('Not Found')
  124. err.status = 404
  125. next(err)
  126. })
  127. app.use((err, req, res, next) => {
  128. res.status(err.status || 500)
  129. _.set(res.locals, 'pageMeta.title', 'Error')
  130. res.render('error', {
  131. message: err.message,
  132. error: WIKI.IS_DEBUG ? err : {}
  133. })
  134. })
  135. // ----------------------------------------
  136. // HTTP/S server
  137. // ----------------------------------------
  138. let srvConnections = {}
  139. app.set('port', WIKI.config.port)
  140. if (WIKI.config.ssl.enabled) {
  141. WIKI.logger.info(`HTTPS Server on port: [ ${WIKI.config.port} ]`)
  142. const tlsOpts = {}
  143. try {
  144. if (WIKI.config.ssl.format === 'pem') {
  145. tlsOpts.key = fs.readFileSync(WIKI.config.ssl.key)
  146. tlsOpts.cert = fs.readFileSync(WIKI.config.ssl.cert)
  147. } else {
  148. tlsOpts.pfx = fs.readFileSync(WIKI.config.ssl.pfx)
  149. }
  150. if (!_.isEmpty(WIKI.config.ssl.passphrase)) {
  151. tlsOpts.passphrase = WIKI.config.ssl.passphrase
  152. }
  153. if (!_.isEmpty(WIKI.config.ssl.dhparam)) {
  154. tlsOpts.dhparam = WIKI.config.ssl.dhparam
  155. }
  156. } catch (err) {
  157. WIKI.logger.error('Failed to setup HTTPS server parameters:')
  158. WIKI.logger.error(err)
  159. return process.exit(1)
  160. }
  161. WIKI.server = https.createServer(tlsOpts, app)
  162. // HTTP Redirect Server
  163. if (WIKI.config.ssl.redirectNonSSLPort) {
  164. WIKI.serverAlt = http.createServer((req, res) => {
  165. res.writeHead(301, { 'Location': 'https://' + req.headers['host'] + req.url })
  166. res.end()
  167. })
  168. }
  169. } else {
  170. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  171. WIKI.server = http.createServer(app)
  172. }
  173. apolloServer.installSubscriptionHandlers(WIKI.server)
  174. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  175. WIKI.server.on('error', (error) => {
  176. if (error.syscall !== 'listen') {
  177. throw error
  178. }
  179. // handle specific listen errors with friendly messages
  180. switch (error.code) {
  181. case 'EACCES':
  182. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  183. return process.exit(1)
  184. case 'EADDRINUSE':
  185. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  186. return process.exit(1)
  187. default:
  188. throw error
  189. }
  190. })
  191. WIKI.server.on('connection', conn => {
  192. let key = `${conn.remoteAddress}:${conn.remotePort}`
  193. srvConnections[key] = conn
  194. conn.on('close', function() {
  195. delete srvConnections[key]
  196. })
  197. })
  198. WIKI.server.on('listening', () => {
  199. if (WIKI.config.ssl.enabled) {
  200. WIKI.logger.info('HTTPS Server: [ RUNNING ]')
  201. // Start HTTP Redirect Server
  202. if (WIKI.config.ssl.redirectNonSSLPort) {
  203. WIKI.serverAlt.listen(WIKI.config.ssl.redirectNonSSLPort, WIKI.config.bindIP)
  204. WIKI.serverAlt.on('error', (error) => {
  205. if (error.syscall !== 'listen') {
  206. throw error
  207. }
  208. switch (error.code) {
  209. case 'EACCES':
  210. WIKI.logger.error('(HTTP Redirect) Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  211. return process.exit(1)
  212. case 'EADDRINUSE':
  213. WIKI.logger.error('(HTTP Redirect) Port ' + WIKI.config.port + ' is already in use!')
  214. return process.exit(1)
  215. default:
  216. throw error
  217. }
  218. })
  219. WIKI.serverAlt.on('listening', () => {
  220. WIKI.logger.info('HTTP Server: [ RUNNING in redirect mode ]')
  221. })
  222. }
  223. } else {
  224. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  225. }
  226. })
  227. WIKI.server.destroy = (cb) => {
  228. WIKI.server.close(cb)
  229. for (let key in srvConnections) {
  230. srvConnections[key].destroy()
  231. }
  232. if (WIKI.config.ssl.enabled && WIKI.config.ssl.redirectNonSSLPort) {
  233. WIKI.serverAlt.close(cb)
  234. }
  235. }
  236. return true
  237. }