master.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 path = require('path')
  10. const session = require('express-session')
  11. const SessionRedisStore = require('connect-redis')(session)
  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. // ----------------------------------------
  22. // Load middlewares
  23. // ----------------------------------------
  24. var mw = autoload(path.join(WIKI.SERVERPATH, '/middlewares'))
  25. var ctrl = autoload(path.join(WIKI.SERVERPATH, '/controllers'))
  26. // ----------------------------------------
  27. // Define Express App
  28. // ----------------------------------------
  29. const app = express()
  30. WIKI.app = app
  31. app.use(compression())
  32. // ----------------------------------------
  33. // Security
  34. // ----------------------------------------
  35. app.use(mw.security)
  36. app.use(cors(WIKI.config.cors))
  37. app.options('*', cors(WIKI.config.cors))
  38. app.enable('trust proxy')
  39. // ----------------------------------------
  40. // Public Assets
  41. // ----------------------------------------
  42. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  43. app.use(express.static(path.join(WIKI.ROOTPATH, 'assets'), {
  44. index: false,
  45. maxAge: '7d'
  46. }))
  47. // ----------------------------------------
  48. // OAuth2 Server
  49. // ----------------------------------------
  50. // const OAuth2Server = oauth2orize.createServer()
  51. // ----------------------------------------
  52. // Passport Authentication
  53. // ----------------------------------------
  54. let sessionStore = new SessionRedisStore({
  55. client: WIKI.redis
  56. })
  57. app.use(cookieParser())
  58. app.use(session({
  59. name: 'wikijs.sid',
  60. store: sessionStore,
  61. secret: WIKI.config.sessionSecret,
  62. resave: false,
  63. saveUninitialized: false
  64. }))
  65. app.use(WIKI.auth.passport.initialize())
  66. app.use(WIKI.auth.passport.session())
  67. // ----------------------------------------
  68. // SEO
  69. // ----------------------------------------
  70. app.use(mw.seo)
  71. // ----------------------------------------
  72. // View Engine Setup
  73. // ----------------------------------------
  74. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  75. app.set('view engine', 'pug')
  76. app.use(bodyParser.json({ limit: '1mb' }))
  77. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  78. // ----------------------------------------
  79. // Localization
  80. // ----------------------------------------
  81. WIKI.lang.attachMiddleware(app)
  82. // ----------------------------------------
  83. // View accessible data
  84. // ----------------------------------------
  85. app.locals.basedir = WIKI.ROOTPATH
  86. app.locals._ = require('lodash')
  87. app.locals.moment = require('moment')
  88. app.locals.moment.locale(WIKI.config.lang.code)
  89. app.locals.config = WIKI.config
  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. })
  105. apolloServer.applyMiddleware({ app })
  106. // ----------------------------------------
  107. // Routing
  108. // ----------------------------------------
  109. app.use('/', ctrl.auth)
  110. // app.use('/graphql', (req, res, next) => {
  111. // graphqlApollo.graphqlExpress({
  112. // schema: graphqlSchema,
  113. // context: { req, res },
  114. // formatError: (err) => {
  115. // return {
  116. // message: err.message
  117. // }
  118. // }
  119. // })(req, res, next)
  120. // })
  121. // app.use('/graphiql', graphqlApollo.graphiqlExpress({ endpointURL: '/graphql' }))
  122. app.use('/', mw.auth, ctrl.common)
  123. // ----------------------------------------
  124. // Error handling
  125. // ----------------------------------------
  126. app.use((req, res, next) => {
  127. var err = new Error('Not Found')
  128. err.status = 404
  129. next(err)
  130. })
  131. app.use((err, req, res, next) => {
  132. res.status(err.status || 500)
  133. res.render('error', {
  134. message: err.message,
  135. error: WIKI.IS_DEBUG ? err : {}
  136. })
  137. })
  138. // ----------------------------------------
  139. // HTTP server
  140. // ----------------------------------------
  141. let srvConnections = {}
  142. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  143. app.set('port', WIKI.config.port)
  144. WIKI.server = http.createServer(app)
  145. WIKI.server.listen(WIKI.config.port)
  146. WIKI.server.on('error', (error) => {
  147. if (error.syscall !== 'listen') {
  148. throw error
  149. }
  150. // handle specific listen errors with friendly messages
  151. switch (error.code) {
  152. case 'EACCES':
  153. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  154. return process.exit(1)
  155. case 'EADDRINUSE':
  156. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  157. return process.exit(1)
  158. default:
  159. throw error
  160. }
  161. })
  162. WIKI.server.on('connection', conn => {
  163. let key = `${conn.remoteAddress}:${conn.remotePort}`
  164. srvConnections[key] = conn
  165. conn.on('close', function() {
  166. delete srvConnections[key]
  167. })
  168. })
  169. WIKI.server.on('listening', () => {
  170. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  171. })
  172. WIKI.server.destroy = (cb) => {
  173. WIKI.server.close(cb)
  174. for (let key in srvConnections) {
  175. srvConnections[key].destroy()
  176. }
  177. }
  178. return true
  179. }