not working

This commit is contained in:
slawk0
2024-08-22 23:02:21 +02:00
parent 5f7ca46c5b
commit d30d5391f2
2 changed files with 43 additions and 19 deletions

View File

@@ -1,5 +1,9 @@
const socket = io();
const socket = io({
auth: {
token: document.cookie.split('=')[1]
}
});
const form = document.getElementById('form');
const input = document.getElementById('input');

View File

@@ -13,7 +13,13 @@ const saltRounds = 10;
const { Server } = require('socket.io');
const { createServer } = require('node:http');
const server = createServer(app);
const io = new Server(server);
const io = new Server(server, {
cookie: {
httpOnly: true,
sameSite: "strict",
maxAge: 30 * 24 * 60 * 60 * 1000
}
});
const jwt = require('jsonwebtoken');
const {decode} = require("jsonwebtoken");
@@ -95,24 +101,38 @@ app.get('/', (req, res) => {
}
const username = user.username;
res.sendFile(path.join(__dirname, '/frontend/routes/chat.html'));
// socket io connection
io.on('connection', (socket) => {
console.log(username + ' connected');
// disconnect event
socket.on('disconnect', () => {
console.log(username + ' have disconnected');
});
// chat message event
socket.on('chat message', (msg) => {
const message = username + ': ' + msg;
console.log(message);
io.emit('chat message', message);
});
});
});
});
// socket io connection
io.use((socket, next) => {
const token = socket.handshake.auth.token;
if (token) {
jwt.verify(token, jwtSecret, (err, decoded) => {
if (err) return next(new Error('Authentication error'));
socket.username = decoded.username;
next();
});
} else {
next(new Error('Authentication error'));
}
});
io.on('connection', (socket) => {
const username = socket.username;
console.log(username + ' connected');
// disconnect event
socket.on('disconnect', () => {
console.log(username + ' have disconnected');
});
// chat message event
socket.on('chat message', (msg) => {
const message = username + ': ' + msg;
console.log(message);
io.emit('chat message', message);
});
})
// run server
server.listen(port, () => {
console.log(`Chat app listening on port ${port}`);
@@ -157,7 +177,7 @@ async function loginUser(req, res) {
// Compare password
const match = await bcrypt.compare(password, result.rows[0].password);
if (match) {
const token = jwt.sign({ username }, jwtSecret, {
const token = jwt.sign({username}, jwtSecret, {
expiresIn: '30d' // token expires in 30 days
});
res.cookie('token', token, {
@@ -189,4 +209,4 @@ async function loginUser(req, res) {
res.send('Please enter Username and Password!');
}
res.end();
}
}