Created
February 12, 2017 17:50
-
-
Save JosephLivengood/a9e69ff91337500d5171e29324e1ff35 to your computer and use it in GitHub Desktop.
FCC Advanced Node and Express Socket.IO Checkpoint 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My Solution for this (works for now)
Require passport.socketio in server.js:
Call the authorize() method on this, giving the options below and mount it using io.use() for all packets.