After struggling a lot with session.socket.io module, I decided to do my socket-session linking by setting authorization for my socket.io. Here is my server:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var io = require('socket.io');
var redis = require('redis');
var crypto = require('crypto');
var redisClient = redis.createClient();
var app = express();
// Session Tracking
var cookieParser = express.cookieParser('secret');
var RadisStore = require('connect-redis')(express);
var sessionStore = new RadisStore({
host: '127.0.0.1',
port: 6379,
db: 10,
client:redisClient
});
// Redis Client Used to store user Information
var redisUsersClient = redis.createClient();
const userDB = require('redis-user')(redisUsersClient);
var PORT = process.env.PORT || 3000,
HOST = process.env.HOST || 'localhost';
// We define the key of the cookie containing the Express SID
var EXPRESS_SID_KEY = 'express.sid';
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
app.use(express.methodOverride());
app.use(cookieParser);
app.use(express.session({ store: sessionStore,
secret: 'SEKR37',
cookie: { httpOnly: true},
key: EXPRESS_SID_KEY
}));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', function(req, res){
if(!req.session.user)
res.redirect('/login')
else {
res.sendfile('chat.html')
}
});
app.get('/login', function(req, res){
res.render('login');
});
app.get('/register', function(req, res){
res.render('register');
});
app.get('/logout', function(req, res){
//console.log(req.session);
sessionStore.destroy(function(err){
console.log("there was an error: "+err);
});
req.session.destroy();
res.redirect('/login');
// redisUsersClient.hdel('users', req.session.user, function(err, reply){
// if(reply==1) {
//
// res.redirect('/login');
// }
// else
// res.send("you do not exist");
// });
});
app.post('/login',function(req, res){
var password = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.password).digest('utf8');
var username = req.body.username+"#mychat.com";
//console.log(req.session);
userDB.validateUser(username, password, function(result){
if(result)
{
req.session.user = username;
req.session.status = 1;
req.session.isLogged = true;
req.session.save();
res.redirect('/');
}
else
{
res.send("Wrong Credential. Please <a href='/login'>Try Again</a>");
}
});
});
app.post('/register',function(req, res){
var username = req.body.username + "#mychat.com";
var password = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.password).digest('utf8');
var verify = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.verify).digest('utf8');
if(password==verify)
{
userDB.createUser(username, password, function(result) {
if (result) {
redisUsersClient.hset('users', username, password);
res.redirect('/');
} else {
res.send("could not create user, Something very unexpected happened");
}
});
}
else
{
res.send("Passwords do not match. please <a href='/register'>try again</a> " );
}
});
server = http.createServer(app);
io = io.listen(server);
/****
Maybe I have to set store for io?
****/
//io.set('store', sessionStore);
io.set('authorization', function (data, accept) {
if(!data.headers.cookie) {
return accept('No cookie transmitted.', false);
}
console.log(sessionStore);
cookieParser(data, {}, function(parseErr) {
if(parseErr) { return accept('Error parsing cookies.', false); }
var sidCookie = (data.secureCookies && data.secureCookies[EXPRESS_SID_KEY]) ||
(data.signedCookies && data.signedCookies[EXPRESS_SID_KEY]) ||
(data.cookies && data.cookies[EXPRESS_SID_KEY]);
console.log(sidCookie);
// Then we just need to load the session from the Express Session Store
sessionStore.load(sidCookie, function(err, session) {
// And last, we check if the used has a valid session and if he is logged in
console.log(session);
if (err || !session) {
accept('Error', false);
}
else {
// If you want, you can attach the session to the handshake data, so you can use it again later
data.session = session;
//console.log('success');
accept(null, true);
}
});
});
});
io.on('connection', function (socket) {
socket.on('add-user',function(data){
console.log(data.username);
clients.username = data.username;
//console.log(clients);
socket.broadcast.emit('entrance', data.username + ' has connected');
io.sockets.emit('add-user',{clients:clients});
});
socket.on('disconnect', function(){
delete clients[session.user];
io.sockets.emit('add-user',{clients:clients})
});
});
server.listen(PORT, HOST, null, function() {
console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
});
And here is my client:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- <script type='text/javascripts', src='/javascripts/client.js'></script> -->
<link rel='stylesheet', href='/stylesheets/style.css'>
<script>
jQuery(document).ready(function () {
var log_chat_message = function (message, type, divId) {
var li = jQuery('<li />').text(message);
if (type === 'system') {
li.css({'font-weight': 'bold','color': '#F00','cursor':'pointer'});
} else if (type === 'leave' || type === 'error') {
li.css({'font-weight': 'bold', 'color': '#F00'});
}
jQuery('#'+divId).append(li);
};
// connect to the socket server
var socket = io.connect();
socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
socket.on('welcome',function(data){
alert("yooooo");
var username = data.username.substr(0,data.username.indexOf('#'));
var message = "Welcome " + username ;
log_chat_message(message, 'system','messages');
socket.emit('add-user',{username: username});
});
socket.on('entrance', function(data){
//var message = data.username.substr(0,data.username.indexOf('#')) + " joined the chat";
log_chat_message(data, 'system','messages');
});
socket.on('add-user', function(data){
jQuery.each(data, function(key, value){
console.log(value.username);
log_chat_message(value.username, 'system','users-list');
})
});
jQuery('#message_input').keypress(function (event) {
if (event.which == 13) {
socket.emit('chat', {message: jQuery('#message_input').val()});
jQuery('#message_input').val('');
}
});
jQuery('#users-list li').on('click','li',function(){
alert('hi');
});
jQuery('#users-list li').click(function () {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
jQuery('#user').val('');
socket.emit('request', {username: jQuery('#user').val()});
});
});
</script>
<style type = 'text/stylesheet'>
#users-list li {
cursor:pointer;
}
</style>
</head>
<body>
<a href='/logout'>Log Out</a>
<div id="wrapper" style="width:80%;margin:0 auto;">
<!-- <input type="text" name="user" id="user"/>
<button id="submit" value="submit">Submit</button> -->
<div id='mainContaner' style="width:600px;height:400px;margin:0 auto;">
<div id="online-users" style="width:150px;float:left;height:400px;padding:20px;border:1px black solid;">
<ul id="users-list" style="list-style:none"></ul>
</div>
<div id= "container" style="width:350px;float:left;height:400px;padding:20px;overflow-y:scroll;border:1px black solid;">
<ul id='messages' style="list-style:none"></ul>
</div>
<input type="text" name="message_input" id='message_input' style="width:390px;height:30px;margin-left:193px;margin-top:5px;"/>
</div>
</div>
</body>
However, I get a handshake error. I am aware that I cannot get my session by loading my session store and that is why the error happens.
Please Advise
You should replace this line
sessionStore.load(sidCookie, function(err, session) {})
with this line
sessionStore.get(sidCookie, function(err, session) {})
This because there's no method load in connect-redis. Only get method
Also when you access your session in socket you can use socket.handshake.session.user
Related
i tried to emplement socket.io but it does not show the way that it should be. Can anyone know where the problem. i tried to solve this around 2 weeks. Its headache to me. I tried many time already which is used emit,write, all of it. this is my code
HTML
<section class="msger" style="margin: auto;">
<header class="msger-header">
<div class="msger-header-title">
<i class="fas fa-comment-alt"></i> Chat
</div>
<div class="msger-header-options">
<span><i class="fas fa-cog"></i></span>
</div>
</header>
<main class="msger-chat" id="msger-chat">
</main>
<form class="msger-inputarea" >
<input type="hidden" name="booking" value="<%= booking %>">
<input type="hidden" id="name" class="form-control" readonly placeholder="Name"
value="<%= user.username %>">
<input type="text" name="user" value="<%= user._id %>">
<input id="message" type="text" class="msger-input" placeholder="Enter your message...">
<button id="send" type="submit" class="msger-send-btn">Send</button>
</form>
</section>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
</div>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Bootstrap core JavaScript-->
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="/js/sb-admin-2.min.js"></script>
<script type="text/javascript" src="/js/mdb.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<!-- Custom scripts -->
<script>
var socket = io();
$(() => {
$("#send").click(() => {
sendMessage({
booking: $("input[name=booking]").val(),
user: $("input[name=user]").val(),
message: $("#message").val()
});
})
getMessages()
})
socket.on('message', addMessages)
function addMessages(message) {
if (message.user && message.user != '') {
if ($("input[name=user]").val() == message.user._id) {
html = '<div class="msg right-msg"><div class="msg-img" style="background-image: url(' + message.user.image +
')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.user.username +
'</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
} else {
html = '<div class="msg left-msg"><div class="msg-img" style="background-image: url(' + message.pro.image +
')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.pro.username +
'</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
html += '<div class="msg-text">' + message.message + '</div></div></div>'
window.scrollTo(0, document.body.scrollHeight);
$("#msger-chat")+$(".msger-chat").append(html)
}
function getMessages() {
$.get('http://127.0.0.1:3000/messageslist/<%=booking%>', (data) => {
data.forEach(addMessages);
})
}
function sendMessage(message) {
$.post('http://127.0.0.1:3000/messages', message)
}
</script>
this is my routes
Route
var http = require('http').Server(router);
var io = require('socket.io')(http);
// Render Message
router.get('/messages/:id', async function (req, res, next) {
user = await User.findOne({_id: req.session.userId}, {username: 1})
return res.render("user/messages.ejs", {user: user, booking: req.params.id});
});
// Display Message from DB
router.get('/messageslist/:booking', (req, res) => {
Message.find({booking: req.params.booking})
.populate({
path: "pro",
model: Pro,
}).populate({
path: "user",
model: User,
}).exec().then((data) => {
res.json(data)
})
})
router.post('/messages', async (req, res) => {
const {booking, user, message} = req.body
try {
var msg = new Message({
booking: booking,
message: message,
user: user
});
var savedMessage = await msg.save()
console.log('saved');
var censored = await Message.findOne({
message: 'badword'
});
if (censored)
await Message.remove({
_id: censored.id
})
else
io.emit('message', req.body);
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
return console.log('error', error);
} finally {
console.log('Message Posted')
}
})
Server
var express = require('express');
var env = require('dotenv').config()
var ejs = require('ejs');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session)
const cookieParser = require('cookie-parser')
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors')
app.use(cors())
app.use(cookieParser());
// mongodb://localhost:27017 127.0.0.1:27017
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/findaprofessional', {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err) => {
if (!err) {
console.log('MongoDB Connection Succeeded.');
} else {
console.log('Error in DB connection : ' + err);
}
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
});
const oneDay = 1000 * 60 * 60 * 24;
app.use(session({
secret: 'work hard',
saveUninitialized:true,
cookie: { maxAge: oneDay },
resave: true
}));
// ni lain
app.set("view engine", "ejs")
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/css', express.static(path.resolve(__dirname, "asset/css")))
app.use('/img', express.static(path.resolve(__dirname, "asset/img")))
app.use('/js', express.static(path.resolve(__dirname, "asset/js")))
app.use('/vendor', express.static(path.resolve(__dirname, "asset/vendor")))
app.use('/lib', express.static(path.resolve(__dirname, "asset/lib")))
app.use('/scss', express.static(path.resolve(__dirname, "asset/scss")))
app.use('/pic', express.static(path.resolve(__dirname, "asset/img/pic")))
var index = require('./routes/index');
const { Socket } = require('socket.io');
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
io.on('connection', () =>{
console.log('a user is connected')
})
var server = http.listen(3000, () => {
console.log('Server is started on http://127.0.0.1:'+ server.address().port);
});
Im expecting someone can go thru my codes and solve the problem. i thinks my problem at html socken.on. but im not sure enough.
I'm new to mean-stack and I followed some instruction on how to get real-time data. I tried every single steps but none of it is working, how can I use socket.io correctly? I provided my code here for getting users from mongodb, please do correct my code
server.js
var express = require ('express');
var app = express();
var server = require('http').Server(app);
var http = require('http').Server(app);
var io = require('socket.io')(http);
var morgan = require ('morgan');
var mongoose = require('mongoose');
var appRoutes = require('./app/routes/api');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.use('/api',appRoutes);
mongoose.connect('mongodb://localhost:27017/testing', function(err){
if(err){
console.log('Not connected' + err);
} else
{
console.log('Connected');
}
});
Then here is the part where I get the users from the table, I don't know how to get the the data real-time:
api.js
var User = require('../models/user');
const router = express.Router();
router.get('/management', function(req, res) {
User.find({}, function(err, users) {
if (!users) {
res.json({ success: false, message: 'Users not found' });
} else {
res.json({ success: true, users: users,});
}
});
});
userCtrl.js
.controller('managementCtrl', function(User, $scope) {
function getUsers() {
User.getUsers().then(function(data) {
if (data.data.success) {
app.users = data.data.users;
} else {
app.errorMsg = data.data.message;
}
});
}
});
users.html
<tbody>
<tr ng-repeat="person in management.users">
<td align="center">{{ person.name }}</td>
<td align="center">{{ person.email }}</td>
</tr>
</tbody>
First of all you need to get a socket with connection event:
io.on('connect', function(socket){
than you need to set a "listener" on specific event you want to reply with data
Together it will be:
io.on('connect', function(socket){
socket.on('eventYouGet', function(eventData) {
User.find({}, function(err, users) {
if (!users) {
socket.emit('eventAnswer', {success: false, message: 'Users not found'});
} else {
socket.emit('eventAnswer', {success: true, users: users)};
}
});
});
});
Where eventYouGet is event which you (from server perspective) are waiting for (kind of like request in REST); eventAnswer is event you send as answer (to the client).
Note:
socket.emit sends an event to sender and no one else (one socket)
On the server -
I generally check for connections:
io.on('connection', function(socket){
console.log('a user connected');
});
You'll need for the client and the server to agree on some sort of token to listen to for socket. In this case, I am hardcoding in '123123123'
var User = require('../models/user');
const router = express.Router();
router.get('/management', function(req, res) {
User.find({}, function(err, users) {
if (!users) {
io.emit("123123123", { success: false, message: 'Users not found' });
} else {
io.emit("123123123", { success: true, users: users,});
}
});
});
In angular -
var socket = io.connect(<url>); //url from server
socket.on('123123123', function (user) {
let user = json.parse(user)
});
While in / view, I get documents from mongodb and create a list item for each document that only shows the date and the first few words. I want to be able to click on each list item to go to a new page, /view, to see the rest of that particular document.
To do this, I believe I need to pass item between / and /view, then access the properties of item there. How do I do this with the pagelist function (or without it)?
index.js:
var express = require('express');
var exphbs = require('express-handlebars');
var bodyParser = require('body-parser');
var app = express();
var hbs = exphbs.create({
helpers: {
message: function() {return 'Welcome!';},
doc: function() {return "Something went wrong.";}
}
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var util=require('util');
const url = 'mongodb://localhost:27017/users';
const dbName = 'users';
var db;
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
db.collection("reviewYelp2", { }, function(err, coll) {
if (err != null) {
console.log(err)
db.createCollection("reviewYelp2", function(err, result) {
assert.equal(null, err);
});
}
db.ensureIndex("reviewYelp2", { document: "text"}, function(err, indexname) {
assert.equal(null, err);
});
});
});
app.get("/", function(req, res) {
res.render('search');
});
app.get("/view", function(req, res) {
// NEED TO BE ABLE TO ACCESS CLICKED ITEM HERE
res.render('viewItem', {
// Change to access item.text when I have access to item
helpers: {
doc: function() {return "Viewing doc...";}
}
});
});
app.post("/", function(req, res) {
db.collection('reviewYelp2').find({
text: new RegExp(req.body.query)
}).sort({date: 1}).toArray(function(err, items) {
res.render('search', {
helpers: {
message: function() {return pagelist(items);}
}
});
})
});
function pagelist(items) {
result = "<ul>";
items.forEach(function(item) {
// Grab only first 10 words of text
textSlice = item.text.split(" ");
textSlice = textSlice.slice(0, 5);
text = textSlice.join(" ");
str = "<li class="+item._id+"><a href='/view'>" + item.date + " " + text + "...</a></li>";
result = result + str;
});
result = result + "</ul>";
return result;
}
app.listen(3000, function() {
console.log("App listening on localhost:3000");
});
search.handlebars:
<!DOCTYPE html>
<html>
<body>
<form method="post">
<input type="text" size="80" name="query" />
<input type="submit" value="Search" class="submitButton" />
{{{ message }}}
</form>
</body>
</html>
viewItem.handlebars:
<!DOCTYPE html>
<html>
<body>
<button onclick="window.history.back()">Go back to list</button>
{{{ doc }}}
</body>
</html>
This is problematic because http is fundamentally stateless — that is each request to the server is it's own thing. You can come up with schemes involving cookies or local storage, but I think a simpler approach is both better and more common.
A simpler idea is to have a route that takes some sort of id parameter:
app.get("/view_detail/:itemID", function(req, res) {
var item = req.params.itemID
// lookup detail about item based on itemID
res.render('viewItem', {
// send data
});
});
Now on index you can have a list of links that look like :
/view/878743 (or whatever scheme you have for db keys)
/view/36764e
I have a problem which is as follows:
If I send a message in English, there is no problem.
But if I send a message in thai language, no message is shown and the message is incorrect eg. input:'ส' program shows: '*'.
I deploy on www.heroku.com
code in github: https://github.com/KraisornRitthiwong/chat
this code:
//app.js
var express = require('express'),
app = express();
var port = process.env.PORT || 3000;
var io = require('socket.io').listen(app.listen(port));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index');
});
io.on('connection', function(socket) {
socket.on('chat', function(data) {
io.emit('chat', data);
});
});
//index.jade
var socket = io();
var chatForm = $('#chat-form');
var chatHistory = $("#chat-history");
var inputMessage = $('#chat-message');
inputMessage.focus();
var username = Math.floor((Math.random() * 100) + 1);
socket.emit('chat', {
username: username,
message: 'I\'m connected.'
});
chatForm.submit(function() {
alert(inputMessage.val());
socket.emit('chat', {
username: username,
message: inputMessage.val()
});
$(this)[0].reset();
return false;
});
socket.on('chat', function(data) {
alert(data.message);
if (data.username == username) {
chatHistory.append($('<li class="message message--me">').text(data.message));
} else {
chatHistory.append($('<li class="message">').text(data.username + ': ' + data.message));
}
chatHistory[0].scrollTop = chatHistory[0].scrollHeight;
});
thank you very much.
I don't understand where is my problem.
When I put this:
io = require('socket.io').listen(server).of("/");
I my handshake looks like running fine, but all my socket.io's event (like connection) never works.
And when I when i put this
io = require('socket.io').listen(server);
I got this :
TypeError: Object # has no method 'authorization'
If I remove my handshake, all the socket.io's will works, but i need it :/
Here my app.js
const express = require('express')
, app = express()
, http = require('http')
, ejs = require('ejs')
, server = http.createServer(app)
, port = process.env.PORT || 1337
, io = require('socket.io').listen(server).of("/")
;
module.exports = { app: app, server: server };
// Grab "cookie" and "connect" from express
var connect = require('express/node_modules/connect')
var cookie = require('express/node_modules/cookie')
var connectes =[];
app.configure(function(){
this.use("/public", express.static(__dirname + '/public'));
this.use(express.cookieParser());
this.use(express.json());
this.use(express.urlencoded());
this.sessionStore = new express.session.MemoryStore({ reapInterval: 60000 * 10 });
this.use(express.session({
"secret": "some private string",
"store": this.sessionStore
}));
});
app.engine('html', ejs.renderFile);
app.set('views', __dirname + '/views');
app.get('/', [requireLogin], function(request, response) {
var pseudo = request.session.pseudo;
response.render('index.ejs.html',{connectes:connectes});
});
app.get('/login', function(request, response) {
response.render('login.ejs.html');
});
app.post("/login", function(req, res){
if (req.param("user") != "") {
req.session.pseudo = req.param("user");
//socket.set('pseudo',req.param("user"));
connectes.push(req.param("user"));
res.render('index.ejs.html',{connectes:connectes});
}else{
res.render('login.ejs.html');
}
});
const parseCookie = require('connect').utils.parseCookie;
io.authorization(function (handshakeData, callback) {
var cookies = cookie.parse(handshakeData.headers.cookie);
console.log(cookie);
});
io.on('connection', function(socket){
console.log("This never appear in log :/");
socket.on('login',function(user,callback){
var pseudoValide = true;
for (var i = 0; i < connectes.length; i++) {
if(connectes[i]==user.pseudo){
pseudoValide = false;
callback(true);
}
}
if (pseudoValide) {
socket.set('pseudo',user.pseudo);
pseudo = user.pseudo;
socket.broadcast.emit('newuser', pseudo);
socket.broadcast.emit('nvluseronline', pseudo);
connectes.push(pseudo);
callback(false,pseudo);
}
});
socket.on('message',function(message){
messageUser = message.message;
socket.get('pseudo',function(error, pseudo){
io.sockets.emit('nouveauMessage',{pseudo:pseudo,message:messageUser});
})
});
socket.on('disconnect',function(){
socket.get('pseudo',function(error, pseudo){
connectes = unset(connectes, pseudo);
io.sockets.emit('nvldisc', pseudo);
})
});
});
function unset(array, value){
var output=[];
var index = array.indexOf(value)
{
var j = 0;
for(var i in array)
{
if (i!=index)
{
output[j]=array[i];
j++;
}
}
return output;
}
}
/** Middleware */
function requireLogin (req, res, next) {
if (req.session.pseudo) {
console.log(req.session.pseudo);
next();
}else{
res.redirect("/login");
}
}
if (!module.parent) {
server.listen(port, function () {
console.log('Listening', this.address());
})
}
Like you can see i'm a beginner lost !
Thank you guys !
You should read the documentation on authorization carefully. authorization method only exists for namespaces. When doing global authorization, you have to do:
io.configure(function (){
io.set('authorization', function (handshakeData, callback) {
callback(null, true); // error first callback style
});
});
It'll work fine if you have .of("/") as server endpoint, but it is a namespace. Without namespaces you would have to use above method.