James Peruggia
James Peruggia

Reputation: 327

Socket.io session variable

I am fairly new to node.js and express and I am trying to build a fairly simple application through phone gap which allows me to have a user login, and save that users socket id to a session, so I can keep track of which user is what id, so I can emit a message to only a certain group of users (Its a game, so I need to emit a message to player 1 and player 2, think of players as pairs I guess?)

I have the following index.js file and this is my view. I can't seem to get it to work how I want, and I am unable to see the user name on my view when I request /login. It just shows as a blank string or undefined.

I tried the following things:

1) Have a socket emit on form submit, then on socket.on('form_submit_done') callback, I would call a javascript form post to the login, which would then check my mongodb for that user, and if valid, go to the gamespace page. This was working until I started to use socket.io

2) I have updated it to handle the db call within the socket itself. On my server I do my db check, then emit back to the client. Based on what I emit, I do a specific window.location.replace(); I am sure there has to be an easier way to do this, but I can't seem to figure it out.

Can anyone give me some pointers or tutorials which I can follow which will make this easier to understand?

index.js

/*jshint laxcomma:true*/

var io = require('socket.io')
  , express = require('express')
  , util = require('util')
  , app = express.createServer()
  , connect = require('express/node_modules/connect')
  , parseCookie = connect.utils.parseCookie
  , MemoryStore = connect.middleware.session.MemoryStore
  , store;


  //middleware 
  app.use(express.bodyParser());


app.configure(function () {
  app.set('views', __dirname + '/views');
  app.use(express.static(__dirname + '/public'));
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(express.cookieParser());
  app.use(express.session({
      secret: 'secret'
    , key: 'express.sid'
    , store: store = new MemoryStore()
  }));
});


/* ==============================================================
*         Database Setup        *
*                 *
* ==============================================================*/
var mong = require('mongoose');
mong.connect('mongodb://127.0.0.1:27017/bravazzo');

var db = mong.connection; 
db.on('error', console.error.bind(console, 'connection error')); 
db.once('open', function callback(){
  console.log("db connection good"); 
});

// database schemas for the mongo db.

var userSchema = new mong.Schema({
  user_name:String, 
  email:String, 
  password:String,
  last_login:Date
});

var game_schema = new mong.Schema({
  _id:{type:Number}, 
  player_1: [mong.Schema.Types.ObjectId], 
  player_2:[mong.Schema.Types.ObjectId],  
  date: Date,
  winner:[mong.Schema.Types.ObjectId]
})

// putting models into variables.
// type = mong.model('name in mongo', schemaName);
var user = mong.model('users', userSchema);
var game = mong.model('games', game_schema);


/* ================================================================
*               Misc Functions                                    
*
* ================================================================*/


app.get('/', function (req, res) {
  res.render('splash', {value: req.session.value});
});

// handle the login post action here.
app.get("/login", function(req, res){
    app.use(express.bodyParser());
    console.log(req);
    res.render('game_dashboard', {pageData: {name: req.session.userName}});
});



app.listen(8080);

io.listen(app).set('authorization', function (data, accept) {
  if (!data.headers.cookie) 
    return accept('No cookie transmitted.', false);

  data.cookie = parseCookie(data.headers.cookie);
  data.sessionID = data.cookie['express.sid'];

  store.load(data.sessionID, function (err, session) {
    if (err || !session) return accept('Error', false);

    data.session = session;
    return accept(null, true);
  });
}).sockets.on('connection', function (socket) {
  var sess = socket.handshake.session;
  socket.log.info(
      'a socket with sessionID'
    , socket.handshake.sessionID
    , 'connected'
  );
  socket.on('go login', function (data) {
    // let us check the login credentials!
    var pwd = data.password;
    var uName = data.userName; 
    // this should be refactored at some point where it does the following:
    // look for username, if can't found redirect with message.
    // if uname is good, check password, if wrong, send to page w/ message
    // incorrect password.
    // else everything is good.
    user.find({user_name:uName, password:pwd }).exec(function(err,results){
      if (!err && results.length > 0){
        // we looged in! good.
        sess.reload(function(){
          sess.value = data.random; 
          sess.userName = uName;
          sess.touch().save();
        });
        socket.emit('login_post', {number: data.ran, data:data, user: uName });
    }
    else{
        socket.emit('login_post',{number:data.ran, data:'splash'});
      }
    }); // end user.find
  }); // send socket.on go login
}); // end on connection

splash.jade

!!! 5
html
  head
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1')
    title="Bravazzo"
    link(rel='stylesheet', href='css/user-styles.css')
    link(rel='stylesheet', href='css/bootstrap.min.css')
    link(rel='shortcut icon', href='favicon.ico')
    link(rel='stylesheet', href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,700')
    script(src='js/jquery.js')
    script(src='/socket.io/socket.io.js')
    script(src='http://code.jquery.com/jquery-latest.js')
    script(src='/js/client.js')
  body
    .splash_spacer
      if value
        h2 your session is #{value}
      else
        h2 set session value !
      form(name='login', type="application/x-www-form-urlencoded", id='login_form', action='/login',method='post')
      .pad_left
        label  Username:
        input(type="text", name="userName")
      .pad_left
        label  Password:
        input(type="password", name="password")
        input(type="hidden", id="random", name="random")
      br
      .pad_left_long
        a(href='/register', class="btn btn-inverse", style="width:55px") Sign Up

          
        input(type="submit", value="Login ",id="login", class="btn btn-inverse" style="width:77px;")
script.
  var socket = io.connect(); 
  var sub = $('#login');
  var randomnumber=Math.floor(Math.random()*1001)

  sub.click(function (e){
    socket.emit('go login',{
      userName: $('#userName').val(),
      password: $('#password').val(),
      ran: randomnumber
    });
  });

  socket.on('login_post', function(data){
    console.log(data.number); 
    console.log(randomnumber);
    if (data.data == 'splash'){
      window.location.replace('/');
    }
    if (data.number == randomnumber)
      window.location.replace('/login');
  });

Upvotes: 4

Views: 3574

Answers (1)

leszek.hanusz
leszek.hanusz

Reputation: 5317

You can use the Session socket module module to be able to:

  • Save and retrieve session information for each user
  • Get all connected users and their session information

Upvotes: 3

Related Questions