-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
83 lines (68 loc) · 2.41 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Dependencies
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const passport = require('passport')
const flash = require('connect-flash')
const morgan = require('morgan')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const http = require('http')
const path = require('path')
const socketIO = require('socket.io')
require('dotenv').config()
// Initializing an Express app
const app = express()
// CORS Configuration
app.use(cors())
// Configure Morgan
app.use(morgan('dev'))
// configuring body-parser
app.use(bodyParser.json()) // handles json post requests
// Configure Passport
app.use(cookieParser())
app.use(session({
secret: process.env.sessionSecert,
name: 'Agora.MikeNabil.net',
proxy: true,
resave: true,
saveUninitialized: true
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(flash())
// Load Passport configuration - Currently not working because of missing tokens
require('./config/passport')(passport)
// Use Passport current user
app.use(function (req, res, next) {
global.currentUser = req.user
res.locals.currentUser = req.user
next()
})
// Loading static assets
app.use(express.static(path.join(__dirname, '/build')))
// Routes
const routes = require('./config/routes')
app.use(routes)
// app.use('/', passport.authenticate('jwt', { session: false }), routes)
app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '/build/index.html')) })
// Socket.io Configuration
const server = http.createServer(app)
const io = socketIO.listen(server)
// Schema & Model for Socket.io
const Message = require('./db/Models/Message.js')
// Socket.io Users
let users = 0
// Socket.io Connection
io.on('connection', (socket) => {
users++
console.log(`${users} users connected.`)
Message.find({}).then(messages => { io.emit('initial messages', messages) })
socket.on('chat message', (msg) => { Message.create({ body: msg }).then((msg) => io.emit('chat message', msg)) })
socket.on('disconnect', () => { users--; console.log(`1 User disconnected. ${users} Users remain connected.`) })
})
// Configuring the Server
// app.listen(process.env.PORT, () => { console.log(`The server is running on port ${process.env.PORT}`) })
server.listen(process.env.PORT, () => { console.log(`The server is running on port ${process.env.PORT}`) })
// Errors formatting
app.use(require('better-express-errors')(app))