-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
98 lines (78 loc) · 2.66 KB
/
app.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const mysql = require('mysql');
const cors = require('cors');
const app = express();
const httpServer = createServer(app);
const createConnection = require('./utils/db');
const jwt = require('jsonwebtoken');
const secretKey = process.env.SECRET_KEY;
const io = new Server(httpServer, { cors: { origin: '*' } });
var onlineCount = 0;
var users = [];
const dependencies = {
io: io,
users: users,
onlineCount: onlineCount
};
const authRoutes = require('./routes/auth.routes');
const messageRoutes = require('./routes/message.routes')(dependencies);
io.use((socket, next) => {
const token = socket.handshake.auth.token;
if (!token) {
return next(new Error("Authentication error: No token provided"));
}
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
return next(new Error("Authentication error: Invalid token"));
}
});
let connection = createConnection();
connection.connect(function (err) {
if (err) throw err;
connection.query('SELECT * FROM users WHERE token = "' + token + '"', function (err, result) {
if (err) throw err;
if (result.length > 0) {
socket.name = result[0].username;
socket.userId = result[0].id;
var user = {
id: result[0].id,
nickname: result[0].nickname,
username: result[0].username
};
let userExists = users.some(user => user.id === socket.userId);
if (!userExists) {
onlineCount++;
users.push(user);
}
next();
} else {
next(new Error("Authentication error: Invalid token"));
}
connection.end();
});
});
});
io.on('connection', (socket) => {
io.emit('onlineCount', onlineCount);
io.emit('users', users);
socket.on('disconnect', () => {
console.log('user disconnected ' + socket.name);
users = users.filter(user => user.id !== socket.userId);
onlineCount--;
io.emit('onlineCount', onlineCount);
io.emit('users', users);
});
socket.on('chat message', (msg, userId) => {
console.log('message: ' + msg);
io.emit('chat message', msg, userId);
});
});
app.use(cors());
app.use(express.json());
app.use('/', authRoutes);
app.use('/', messageRoutes);
httpServer.listen(process.env.PORT || 3001, () => {
console.log('listening on *:' + (process.env.PORT || 3001));
});