Problem with Session and Nodejs

4

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);
});
    
asked by anonymous 03.07.2015 / 03:33

1 answer

2

Just to confirm, first of all start installing the libraries:

npm install express socket.io cookie-parser express-session ejs --save

I'll give you an example here of how the use of session creates the app.js:

const KEY = 'nome-do-cookie';
const SECRET = 'chave-secreta-aqui!';

var express = require('express')
  , cookieParser = require('cookie-parser')
  , expressSession = require('express-session')
  , app = express()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server)
  , cookie = cookieParser(SECRET)
  , store = new expressSession.MemoryStore()
;

// Configurando middlewares de Session e Cookie no Express
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(cookie);
app.use(expressSession({
  secret: SECRET, 
  name: KEY, 
  resave: true, 
  saveUninitialized: true,
  store: store
}));

// Compartilhando a sessão válida do Express no Socket.IO
io.use(function(socket, next) {
  var data = socket.request;
  cookie(data, {}, function(err) {
    var sessionID = data.signedCookies[KEY];
    store.get(sessionID, function(err, session) {
      if (err || !session) {
        return next(new Error('Acesso negado!'));
      } else {
        socket.handshake.session = session;
        return next();
      }
    });
  });
});

// Rota para acessar a página principal
app.get("/", function(req, res){
  // Armazenando o nome na sessão.
  req.session.nome = "Usuario";
  res.render('index');
});

// Iniciando uma conexão com Socket.IO.
io.sockets.on('connection', function (client) {
  // Recuperando uma sessão Express.
  var session = client.handshake.session;

  client.on('toServer', function (msg) {
    msg = "<b>" + session.nome + ":</b> " + msg + "<br>";
    client.emit('toClient', msg);
    client.broadcast.emit('toClient', msg);
  });
});

server.listen(3000, function(){
  console.log("Rodando o server!");
});

The client would use this screen:

    <html>
  <body>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io('http://localhost:3000');
        socket.on('toClient', function (msg) {
        var chat = document.getElementById('chat');
        chat.innerHTML += msg;
      });
      var enviar = function() {
        var msg = document.getElementById('msg');
        socket.emit('toServer', msg.value);
      };
    </script>
    <section>
      <pre id="chat"></pre>
      <input type="text" id="msg" placeholder="Sua mensagem">
      <input type="button" onclick="enviar();" value="Enviar">
    </section>
  </body>
</html>

So everytime the connection crashes the user logs back in, the mysql part would be to use the user to log in and use that user to open the connection.

    
06.07.2015 / 14:21