I am creating a chat with node and session , but I have the following problem: the user identifies and enters the room there all right. I am testing on 2 different computers. When I do a refresh on the page it assumes the session of the last user who logged in.
I want to make sure that when the internet falls, it will come back logged, with its information.
app.js - Server _
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var PORT = process.env.PORT || 5000;
var session = require('express-session');
var bodyParser = require('body-parser');
app.use(session({secret: 'ssshhhhh',saveUninitialized: true,resave: true}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var sess;
nicknames = [];
var nickname;
var mysql = require('mysql');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'chat'
});
app.post('/',function(req,res){
sess=req.session;
sess.name=req.body.name;
sess.senha=req.body.senha;
connection.query('SELECT * from login where nome="'+sess.name+'" and senha ="'+sess.senha+'"', function(err, rows, fields) {
if (!err) {
for (var i in rows) { var tot = i;}
if(tot == 0)
{
if (nicknames.indexOf(sess.name) != -1){
console.log("ja existe o usuario : %s",sess.name);
res.redirect('http://localhost/?erro=2'); // caso o usuario ja esteja on
} else{
nicknames.push(sess.name);
nickname = sess.name;
res.redirect('http://localhost/home.php'); // caso tudo ocorra certo
}
}else {
res.redirect('http://localhost/?erro=1'); // caso usuario e senha errado
}
}else {
console.log('Error while performing Query.');
res.redirect('http://localhost/?erro=3'); // caso erro no mysql
}
});
});
io.on('connection',function(socket){
console.log("usuario id : %s",socket.id,' nome:',nickname);
updateNicknames();
function updateNicknames(){
io.sockets.emit('usernames', nicknames);
}
var channel = 'channel-a';
socket.broadcast.emit('message','El usuario '+nickname+' se ha conectado!','System');
socket.join(channel);
socket.on('message',function(msj){
io.sockets.in(channel).emit('message',msj,nickname);
});
socket.on('disconnect',function(){
console.log("Desconectado : %s",socket.id,' nome:',nickname);
nicknames.splice(nicknames.indexOf(nickname), 1);
updateNicknames();
});
socket.on('change channel',function(newChannel){
socket.leave(channel);
socket.join(newChannel);
channel = newChannel;
socket.emit('change channel',newChannel);
});
});
http.listen(PORT,function(){
console.log('el servidor esta escuchando el puerto %s',PORT);
});