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