Skip to content

Instantly share code, notes, and snippets.

@JosephLivengood
Created February 12, 2017 17:50
Show Gist options
  • Save JosephLivengood/a9e69ff91337500d5171e29324e1ff35 to your computer and use it in GitHub Desktop.
Save JosephLivengood/a9e69ff91337500d5171e29324e1ff35 to your computer and use it in GitHub Desktop.
FCC Advanced Node and Express Socket.IO Checkpoint 1
'use strict';
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const auth = require('./app/auth.js');
const routes = require('./app/routes.js');
const mongo = require('mongodb').MongoClient;
const cookieParser= require('cookie-parser')
const passport = require('passport');
const sessionStore= new session.MemoryStore();
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const passportSocketIo = require("passport.socketio");
fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'pug')
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
key: 'express.sid',
store: sessionStore,
}));
mongo.connect(process.env.DATABASE, (err, db) => {
if(err) console.log('Database error: ' + err);
auth(app, db);
routes(app, db);
http.listen(process.env.PORT || 3000);
//start socket.io code
io.use(passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'express.sid',
secret: process.env.SESSION_SECRET,
store: sessionStore
}));
var currentUsers = 0;
io.on('connection', socket => {
++currentUsers;
console.log('user ' + socket.request.user.name + ' connected');
io.emit('user count', currentUsers);
socket.on('disconnect', () => {
--currentUsers;
io.emit('user count', currentUsers);
});
});
//end socket.io code
});
@ganeshh123
Copy link

My Solution for this (works for now)
Require passport.socketio in server.js:

let passportSocketIo = require('passport.socketio')

Call the authorize() method on this, giving the options below and mount it using io.use() for all packets.

io.use(passportSocketIo.authorize({
  cookieParser: cookieParser,
  key:          'express.sid',
  secret:       process.env.SESSION_SECRET,
  store:        sessionStore
}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment