I'm trying to create a private tchat room using the concept of socket.io rooms. When the user clicks on a name of another user, a comparaison will start,if there is a room which contains both users, then it will join the room, otherwise a new room with both users will be created.
When a message arrives, the message is sent to the corrsponding room, but my code doesn't work: the comparaison is done, the corresponding ids are found, but the messages are send for everyone connected to the tchat.
Here is the code of the server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var port = process.env.PORT || 8080;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
//session-store
var MongoStore = require('connect-mongo')(session);
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);
var Room = require('./app/models/room');
var User = require('./app/models/user');
//session
var sessionMiddleware = session({
secret: 'anystringoftext',
saveUninitialized: true,
resave: true,
store: new MongoStore({
mongooseConnection: mongoose.connection
}),
ttl: 2 * 24 * 60 * 60
});
//fonction btoa
var btoa = require('btoa');
var atob = require('atob');
//session with socket.io
io.use(function(socket, next) {
sessionMiddleware(socket.request, {}, next);
});
io.on('connection', function(socket) {
socket.on('startchat', function(name) {
//my id
var idUser = socket.request.session.passport.user;
//search for my name
User.findById(idUser, function(err, user) {
if (err) throw err;
if (user) {
//my name
nameUser = user.local.username;
if (name < nameUser) {
var users = name + ',' + nameUser;
} else {
var users = nameUser + ',' + name;
}
//encrypt the string
var roomid = btoa(users);
//searching fo ra corresponding id
Room.find(function(err, room) {
if (err) throw err;
if (room) {
var dRoom = '';
room.forEach(function(room) {
var idRoom = atob(room.id).split(',');
//comparaison
if ((idRoom[0] == nameUser && idRoom[1] == name) || (idRoom[0] == name && idRoom[1] == nameUser)) {
dRoom = room.id;
console.log(idRoom, room.id);
//join the room
socket.join(dRoom);
}
});
if (dRoom == '') {
//we didn't find an id which corresponds so we create a room with this id
dRoom = roomid;
var newroom = new Room({
id: roomid
});
newroom.save();
console.log('created');
console.log(atob(roomid).split(','));
console.log(roomid);
//join the room
socket.join(roomid);
}
}
//when msg is emitted
socket.on('message', function(msg) {
console.log('message', dRoom);
//emit the msgs to this room
io.sockets.in(dRoom).emit('msg', msg);
});
});
}
});
});
app.use(express.static('public'));
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(sessionMiddleware);
//passport and sessions
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.set('view engine', 'ejs');
require('./app/routes.js')(app, passport);
server.listen(port, function() {
console.log('Server running on port: ' + port);
});
the client.js
$(document).ready(function(){
var socket = io();
socket.on('connect', function() {
// Connected, let's sign-up for to receive messages for this room
$('#chat').hide();
var start;
window.start = function (id,name){
$('#chat').show();
$('#chatHeader').html(name);
socket.emit('startchat', name);
}
$('#send').submit(function(event){
event.preventDefault(); //empeche la page de se recharger
var msg = $('#message').val();
if(msg !== ''){
socket.emit('message', msg);
}
$('#message').val('');
});
});
socket.on('msg', function(msg){
$('.messages').append('<div>'+ msg + '</div>');
});
});
Related
i am finish sessionStore with MongoStore every login is being performed correctly and sessions are being written to the database without errors. I am using this package github.com/jfromaniello/passport.socketio to align the passport with socket io but I have already looked for several places about how after login make the treatment of the sessionStorageso it lists which users with names are online and offline, Could show me a light on this?
app.js
var express = require('express');
var mongoose = require('mongoose');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
const MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var logger = require('morgan');
var passport = require('passport');
var passportSetup = require('./passport-setup');
// import routes
var routes = require('./routes');
// setup express app
var app = express();
app.use(logger());
// setup connection with mongodb
mongoose.connect( process.env.MONGODB_URI || "mongodb://smachs:***#d***.mlab.com:****/****-messenger",
(err, db)=> {
if (err) return new Error(err);
console.log('🔐 Conexão estabelecida com banco de dados!');
});
// setup passport from different class
passportSetup();
// set view engine and connection of application
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());
// session storage based in mongodb
var sessionStore = new MongoStore({
url: 'mongodb://smachs:***#d***.mlab.com:****/****-messenger',
ttl: 1 * 24 * 60 * 60, // = 1 days. Default
autoReconnect: true
})
// setup session based in express-session
app.use(session({
secret:"58585858585858",
key: "connect.sid",
resave: false,
saveUninitialized: false,
store: sessionStore
}));
app.use(flash());
// public directory
app.use(express.static(__dirname + '/public'));
// passport staff
app.use(passport.initialize());
app.use(passport.session());
// start routes
app.use(routes);
// start server
var port = process.env.PORT || 3000;
var server = app.listen(port, () => { console.log('🌐 Servidor iniciado em localhost:', port); });;
// setup socket.io and passport.socketio packages
var io = require('socket.io').listen(server);
var passportSocketIo = require("passport.socketio");
// setup session found in express-session
io.use(passportSocketIo.authorize({
cookieParser: cookieParser, // the same middleware you registrer in express
key: 'connect.sid', // the name of the cookie where express/connect stores its session_id
secret: '58585858585858', // the session_secret to parse the cookie
store: sessionStore, // we NEED to use a sessionstore. no memorystore please
success: onAuthorizeSuccess, // *optional* callback on success - read more below
fail: onAuthorizeFail, // *optional* callback on fail/error - read more below
}));
// setup route just for clients authenticate
function ensureAutheticated(req, res, next) {
if (req.isAuthenticated()) next();
else {
req.flash("info", "Você precisa estar logado para visualizar essa página!");
res.redirect('/login');
}
}
// setup current online clients
var User = require('./models/user');
app.use((req, res, next) => {
res.locals.currentUser = req.user;
res.locals.errors = req.flash('error');
res.locals.infos = req.flash('info');
next();
});
// callback from passport.socketio
function onAuthorizeSuccess(data, accept) {
console.log('🗲 Passport-Socket.IO conectado com sucesso');
io.on('connection', function (socket) {
console.log("🗲 Socket.IO-Native conectado com sucesso");
});
// get current user online after authentication
io.on('connection', function (socket) {
// get user details of documents in database
app.get('/user-online', ensureAutheticated, (req, res) => {
User.find()
.sort({ createdAd: 'descending' })
.exec((err, users) => {
if (err) return next(err);
// render response
res.send({
users: users
})
});
});
});
accept();
}
function onAuthorizeFail(data, message, error, accept) {
console.log('failed connection to socket.io:', data, message);
if (error)
accept(new Error(message));
}
user.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
const SALT_FACTOR = 10;
var userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
displayName: String,
bio: String
});
userSchema.methods.name = function() { return this.displayName || this.username;}
function noop() { };
userSchema.pre('save', function(done) {
var user = this;
console.log('USER: ' + JSON.stringify( user));
if (!( user.isModified('password'))) return done();
bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
if (err) return done(err);
bcrypt.hash(user.password, salt, noop,
function (err, hashedPassword) {
if (err) return done(err);
user.password = hashedPassword;
done();
});
});
});
userSchema.methods.checkPassword = function(guess, done){
bcrypt.compare(guess, this.password, function(err, isMatch){
done(err,isMatch);
});
};
var User = mongoose.model('User', userSchema);
module.exports = User;
I was trying after login to make an query in a collection to list the users I logged but it is limited to only 1 user and gives me no option to treat this result better, thank you very much for the help they give me!
You can track connection, disconnect, login and logout events to create a list of online users.
You can manage online users in RAM or you can use redis for that. Following code snippet may help you achieve your goal -
// Store userIds here
let onlineUsers = [];
io.on('connection', function (socket) {
socket.on('login', (userTokenOrId) => {
// store this to onlineUsers or redis
// Other stuff
});
socket.on('logout', (userTokenOrId) => {
// remove this from onlineUsers or redis
// Other stuff
});
socket.on('disconnect', (userTokenOrId) => {
// remove this from onlineUsers or redis
// Other stuff
});
});
For better use, You can manage one array of objects to store userId and list of socketIds for same and one object to map socketId to userId. This way you can track is one user is online on different browsers/system.
In my project i am using nodejs (express), react js and socket.io to develop a chatting application. But i am not able to get "correct sessionid" inside my socket function (io.use).
In server.js file there are routes and functions to handle socket connections.
In my project i had started my express-session inside login.js file.
Then after successfull login...i am redirecting to home.js, which intern returns home.html.
home.html contains js file, which is having react code and also have socket connections.
server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var DIST_DIR = path.join(__dirname, "bin");
var express = require('express');
//Getting session store
var session = require('express-session');
var cookieParser = require('cookie-parser');
var sessionStore = new session.MemoryStore();
var handshakeData ={};
var cookie = require('cookie');
//Importing routes
var login = require('./routes/login.js');
var registration = require('./routes/registration.js');
var home = require('./routes/home.js');
//Getting cookies from request header. so that from it we can get sessionid.
io.use(function(socket, next) {
handshakeData = socket.request;
var cookies = cookie.parse(handshakeData.headers.cookie);
//Bringing sessionid and storing in a global variable
console.log("***********************Server*********************");
console.log("");
console.log('All cookies parsed in io.use ( %s )', JSON.stringify(cookies));
handshakeData.sessionID = cookies['connect.sid'].split('.')[0].split(':'[1];
console.log('All cookies parsed at server ( %s )', JSON.stringify(cookies));
console.log('Session id at server cookie value in io.use( %s )',
JSON.stringify(handshakeData.sessionID));
next();
});
//Bringing session data by sending "sessionid" to sessionStore
(MemoryStore)place
io.on('connection', function(socket){
sessionStore.get(handshakeData.sessionID, function (err, session) {
handshakeData.session = session;
//Now we can retrieve all session data. But sessionID sent was
not correct
});
console.log('user connected');
socket.on('new message', function(msg){
console.log('Server recieved new message: '+msg);
io.emit('new message', msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
app.use('/', login);
app.use('/registration', registration);
app.use('/home', home);
http.listen(8080, function(){
console.log("listening on port 8080");
});
login.js
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var cookieParser = require('cookie-parser');
var session = require('express-session');
var sessionStore = new session.MemoryStore();
var login_success = 0;
router.use(cookieParser());
router.use(session({ cookie: {
maxAge : 24*60*60*1000
},
store: sessionStore,
saveUninitialized: true,
resave: true,
secret: '1234567890QWERT'
}));
router.get('/', function(req, res){
console.log("Actual session id before login: "+ req.sessionID);
//Clearing cookies at client side.
res.clearCookie("login_message");
res.clearCookie("connect.sid");
res.clearCookie("io");
res.clearCookie("user_name");
res.clearCookie("user_id");
if (login_success == 2)
{
res.cookie('login_message', 'incorrectCredentials');
login_success = 0;
}
res.sendFile(path.join(SRC_DIR,"login.html"));
// res.sendFile(path.join(__dirname, '../bin', 'login.html'));
});
router.post('/', urlencodedParser, function(req, res){
console.log("database called");
//Fetching form data
var username = req.body.loginusername;
var password = req.body.loginpassword;
//Connection string to datanbase
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/WebChat";
//Comparing username and password.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var query = { email: username, password: password };
db.collection("Profile").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
if (result.length != 0)
{
console.log("login success");
login_success = 1;
//Setting session variables
req.session.userid = username;
req.session.username= result[0].firstname;
console.log("***********************Login*********************");
console.log("");
console.log("Actual session id at login: "+ req.sessionID);
console.log("Session userid at server set to :"+ req.session.userid);
console.log("Session name at server set to :"+ req.session.username);
//res.sendFile(path.join(SRC_DIR,"home.html"));
// res.status(200).send(req.session);
console.log("Session reload called");
res.redirect('/home');
}
else
{
//**It is for when user come to login page with entering wrong credentials
login_success = 2;
console.log("login failed");
res.redirect('http://localhost:8080');
}
});
});
});
//export this router to use in our server.js
module.exports = router;
home.js
var express = require('express');
var router = express.Router();
var path = require("path");
var SRC_DIR=path.join(__dirname, "../src/views");
var session = require('express-session');
cookie = require('cookie');
var cookieParser = require('cookie-parser');
var sessionStore = new session.MemoryStore();
var handshakeData ={};
router.use(cookieParser());
router.use(session({ cookie: {
maxAge : 24*60*60*1000
},
store: sessionStore,
saveUninitialized: true,
resave: true,
secret: '1234567890QWERT'
}));
router.get('/', function(req, res){
//setting cookie at client side
res.clearCookie("user_id");
res.clearCookie("user_name");
res.cookie('user_id', req.session.userid);
res.cookie('user_name', req.session.username);
// res.status(200).send(req.session);
console.log(" session reload called");
setTimeout(function(){
res.sendFile(path.join(SRC_DIR,"home.html"));
}, 5000);
console.log("***********************Home*********************");
console.log("");
console.log("Actual session id at home: "+ req.sessionID);
console.log("Cookie userid at client set to :"+ req.session.userid);
console.log("Cookie username at client set to :"+ req.session.username);
});
//export this router to use in our server.js
module.exports = router;
home.jsx (client side file)
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {messages: [],socket: io.connect('http://localhost:8080')};
this.send = this.send.bind(this)
}
}
export default Home
Ouput when exicuting "node server.js":
output
In the above output...
1. login page we got two different session ids (before login and after login).I don't know why this is happening
2. While accessing the session variable inside "server.js", in "io.use" function... we again getting old session id, which was set before login.But with this i can't get my session variable. Because i need to pass new session variable in order to access session variable inside sessionStore.get.
Please help. i have been trying this for 3 days.
Thanks in advance.
I am using formdata to have multipart data and for that i am using busboy-body-parser. But somehow the body is not accessible and the value is undefined.
app.js
var express = require('express');
var mongoose = require('mongoose');
var Uploader = require('s3-image-uploader');
var config = require('./config.js');
var busboyBodyParser = require('busboy-body-parser');
var uploader = new Uploader({
aws: {
key: config.awsKey,
secret: config.awsSecret
},
websockets: false
});
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var multer = require('multer');
// var uuid = require("uuid");
var app = express();
var morgan = require('morgan');
var path = require('path');
var port = process.env.PORT || 3000;
var foodtrucklist = require('./controller/foodtrucklist.js');
var login = require('./controller/login.js');
var itemInfo = require('./controller/item_info.js');
var review = require('./controller/reviews.js');
var popularitems = require('./controller/popularitems.js');
var foodtruck = require('./model/datafoodtruck');
var truckData = require('./model/foodtruck.js');
var webToken = require('./controller/webtoken.js');
var userprofile = require('./controller/userprofile.js');
var notificationdata = require('./model/dataNotifications.js');
var notification = require('./controller/notifications.js');
var foodtruckItemList = require('./controller/item_list_foodtruck.js');
var orderList = require('./controller/orders_foodtruck.js');
var ordermanagement = require('./controller/ordermanagement.js');
var db = mongoose.connect(config.local_mongo_url);
mongoose.connection.once('connected', function() {
console.log("Connected to database")
// foodtruck.save();
// notificationdata.save();
});
app.use(bodyParser.urlencoded({
extended: true
}));
// app.use(multipartyMiddleware);
app.post('/testupload', function(req, res) {
// var file = req.files.file;
// var stream = fs.creatReadStream(req.files.file.path);
// return s3fsImpl.writeFile(file.originalFilename, stream).then(function() {
// console.log(file);
// return;
// fs.unlink(file.path, function(err) {
// if (err) console.error(err);
// res.json({
// status: '200',
// message: 'uploaded'
// });
// });
// })
res.connection.setTimeout(0);
uploader.upload({
fileId: 'someUniqueIdentifier',
bucket: 'quflip',
source: './public/images/food-3-mdpi.png',
name: 'food-3-mdpi.png'
},
function(data) { // success
// console.log('upload success:', data);
res.json({
status: '200',
message: 'image uploaded successfully'
});
},
function(errMsg, errObject) { //error
// console.error('unable to upload: ' + errMsg + ':', errObject);
res.json({
status: '404',
message: 'image is not uploaded successfully'
});
});
});
// app.use('/public/images', express.static(__dirname + '/public/images'));
app.use(morgan('dev'));
// app.use(bodyParser.urlencoded({extended: true}));
app.get('/foodtrucklist', foodtrucklist);
app.post('/itemInfo', itemInfo.itemInfo);
app.post('/likeitem', itemInfo.likeItem);
app.get('/popularitems', popularitems);
app.post('/notification', notification);
app.post('/submitreview', review.addreview);
app.post('/getreview', review.getReview);
app.post('/addOrder', ordermanagement.addOrder);
app.post('/orderHistory', ordermanagement.orderHistory);
app.post('/cancelOrder', ordermanagement.cancelOrder);
app.post('/getOrderStatus', ordermanagement.getOrderStatus);
app.post('/rateOrder', ordermanagement.rateOrder);
app.post('/updateUser', userprofile.updateUser);
app.post('/getUserInfo', userprofile.getUserInfo);
app.post('/createToken', webToken.createToken);
app.post('/checkToken', webToken.checkToken);
app.post('/itemList', foodtruckItemList.getItemList);
app.post('/updateItemStatus', foodtruckItemList.updateItemStatus);
app.post('/addItem', foodtruckItemList.addItem);
app.post('/deletItem', foodtruckItemList.deletItem);
app.post('/orderlist', orderList.getOrderList);
app.post('/statusOrderlist', orderList.getStatusOrderList);
app.post('/updateorder', orderList.updateOrder);
app.use(bodyParser.urlencoded({extended: false}));
app.use(busboyBodyParser({ limit: '50mb' }));
app.post('/login', function(req,res) {
console.log("body" + req.body.email_id + "file" + req.files);
});
app.listen(port, function() {
console.log('express listining on port' + port);
});
so, how can I access body parameters even I tried to use multer but the problem was same.
Busboy has parameters inside busboy.on('field') event
We explicitly have to attach it to req.body before Busboy.on('finish') event like so :
busboy.on('field', (fieldName, value) => {
req.body[fieldName] = value
})
This will attach parameters to req.body as it should be !
I am making my first app in node.js,express.js,express-session.js and angular.js.
I have made a simple login feature in it. A user logs in and can see all his online friends.
The problem that i am facing is that i open one window in chrome and the other in firefox. login from different accounts but friends are shown(in both browser windows) who has the latest login. How to handle this problem?
Here is my server.js file
var app = require("express")();
var session = require('express-session');
var mysql = require("mysql");
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require("socket.io")(http);
//initialize the session
app.use(session({
secret: "online",
resave: true,
saveUninitialized: true
}));
var session_data;
app.use(require("express").static('data'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
/* Creating MySQL connection.*/
var con = mysql.createPool({
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : '',
database : 'testDbChat'
});
app.get("/",function(req,res){
res.sendFile(__dirname + '/data/messages.html');
});
/* Socket connectes ur machine to server */
io.on('connection',function(socket){
socket.on('update_list',function(data){
//data.purpose;
console.log(data);
if((String(data.purpose.trim()))=='list friends'){
var query="update members set online = ? where id = ?";
con.query(String(query),['Y',data.id],function(err,rows){
// var query="select * from user where id !='"+data.id+"'";
var query="SELECT members.FirstName,members.LasName,members.ID,friends.FriendsTwoID,friends.FriendOneID FROM friends JOIN members ON members.ID = friends.FriendsTwoID OR members.ID = friends.FriendOneID WHERE (friends.FriendOneID = '"+data.id+"' OR friends.FriendsTwoID = '"+data.id+"') AND (friends.`Status` = 'Confirmed' AND members.ID != '"+data.id+"')";
con.query(String(query),function(err,rows){
io.emit('logout update',JSON.stringify(rows));
});
});
}
else{
var query="update members set online = ? where id = ?";
con.query(String(query),['N',data.id],function(err,rows){
//var query="select * from user where id !='"+data.id+"'";
var query="SELECT members.FirstName,friends.FriendsTwoID From friends JOIN members ON members.ID = friends.FriendsTwoID where friends.FriendOneID ='"+data.id+"' AND friends.Status = 'Confirmed' ";
con.query(String(query),function(err,rows){
io.emit('logout update',JSON.stringify(rows));
});
});
}
});
});
app.post('/get_list', function (req, res) {
var query="select * from friends";
con.query(String(query),function(err,rows){
res.write(JSON.stringify(rows));
res.end();
});
});
app.post('/login', function (req, res) {
session_data=req.session;
console.log(req.session); // depricated
data = {
name:req.body.name,
password:req.body.password
};
console.log(data);
session_data.password=data.password;
session_data.name=data.name;
var obj={};
var query="select * from members where Username = '"+data.name+"' and Password='"+data.password+"'";
con.query(String(query),function(err,rows){
if(rows.length > 0){
console.log(rows[0].ID);
var un=new Buffer(String(rows[0].FirstName)).toString('base64');
var ui=new Buffer(String(rows[0].ID)).toString('base64');
obj.path_name="/messages.html#?un="+un+"&ui="+ui;
res.write(JSON.stringify(obj));
res.end();
}else{
obj.path_name="invalid";
res.write(JSON.stringify(obj)); // writes the response but has to be sent by response.end
res.end();
}
});
});
app.get('/messages', function (req, res) {
session_data=req.session;
if(session_data.name){
res.sendFile(__dirname + '/data/messages.html');
}else{
res.redirect('/');
}
});
app.post('/logout', function (req, res) {
var query="update members set online = ? where id = ?";
con.query(String(query),['N',req.body.id],function(err,rows){});
req.session.destroy(function(err){
res.end();
});
});
app.get('/home', function (req, res) {
session_data=req.session;
console.log(session_data);
if(session_data.name){
res.sendFile(__dirname + '/data/messages.html');
}else{
res.redirect('/');
}
});
http.listen(3000,function(){
console.log("Listening on 3000");
});
I'm making a Node.js app and I need to create a new document in mongoDB inside socket.io.
I have to insert the logged in user in the new document.
How can I access the session variable inside socketio ?
// INCLUDE MODULES =======================================================
var SocketIOFileUpload = require("socketio-file-upload");
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io');
var Twig = require('twig');
var twig = Twig.twig;
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var Cookies = require( "cookies" );
var flash = require('connect-flash');
var configDB = require('./config/database.js');
var connect = require('connect');
var ImageFile = require('./app/models/image');
// Assets ================================================================
app.use(express.static(path.join(__dirname, 'public')));
app.use(connect.favicon(path.join(__dirname, 'public/images/favicon.ico')));
// Start mongoose
mongoose.connect(configDB.url);
// USER MANAGEMENT =======================================================
require('./config/passport')(passport); // pass passport for configuration
app.use(connect.logger('dev')); // log every request to the console
app.use(connect.cookieParser()); // read cookies (needed for auth)
app.use(connect.json()); // to support JSON-encoded bodies
app.use(SocketIOFileUpload.router); //socket io file upload
app.use(connect.urlencoded()); // to support URL-encoded bodies
app.set('view engine', 'twig'); // set up twig for templating
app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
// Some more code ...
//SOCKET IO =======================================================
//Quand on client se connecte, on le note dans la console
var io = socketio.listen(server);
io.sockets.on("connection", function(socket){
// Make an instance of SocketIOFileUpload and listen on this socket:
var session = socket.handshake.session;
var uploader = new SocketIOFileUpload();
uploader.dir = "/LeafStore/public/uploads";
uploader.listen(socket);
console.log(socket.handshake.user);
// Do something when a file is saved:
uploader.on("saved", function(event, socket){
console.log(event.file);
});
// Do something when a file is saved:
uploader.on("complete", function(event){
console.log("saving file" + name);
console.log(event);
var name = event.file.name;
var imageData = {
name: name
, type: "image"
, userId: ""
, creationDate: new Date()
};
var newImage = new ImageFile(imageData);
newImage.save( function(error, data){
if(error){
throw error;
}
else{
}
});
// save the user
newImage.save(function(err) {
if (err)
throw err;
});;
});
// Error handler:
uploader.on("error", function(event){
console.log("Error from uploader", event);
});
});
// LISTEN SERVER =======================================================
server.listen(80);
I found a temporary solution :
I emit the user Id in my views :
socket.emit('userId', $("#userId").val());
Then I set the socket.userId var :
socket.on('userId', function(userId){
socket.userId = userId;
});
But it's probably unsafe