Problem with Session and Nodejs

Asked

Viewed 1,642 times

4

I’m creating a chat with Node and Session, but I have the following problem: the user identifies and enters the room until then everything right. I am testing on 2 different computers. When I give 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 already comes logged in, with its proper 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);
});

1 answer

2


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

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

I’ll do 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 customer 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 every time the connection drops the user back logged in, the mysql part, would use identify the user who logged in and use that user to open the connection.

  • perfect guy... now the browser does not connect automatic if I stop the application? / When I kill the service in ssh the browser does not a reconect... if I give refresh everything right, user and password identified the part of the perfect refresh ta... only when the server falls it does not reconnect

Browser other questions tagged

You are not signed in. Login or sign up in order to post.