master.js 7.9 KB

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