Skip to content

Instantly share code, notes, and snippets.

@camperbot
Forked from ShaunSHamilton/server.js
Last active August 27, 2022 10:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save camperbot/1414cc9433044e306dd7fd0caa1c6254 to your computer and use it in GitHub Desktop.
Save camperbot/1414cc9433044e306dd7fd0caa1c6254 to your computer and use it in GitHub Desktop.
Advanced Node and Express - Authentication with Socket.IO
'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const session = require('express-session');
const passport = require('passport');
const routes = require('./routes');
const auth = require('./auth.js');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const passportSocketIo = require('passport.socketio');
const cookieParser = require('cookie-parser');
const MongoStore = require('connect-mongo')(session);
const URI = process.env.MONGO_URI;
const store = new MongoStore({ url: URI });
app.set('view engine', 'pug');
fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { secure: false },
key: 'express.sid',
store: store
}));
app.use(passport.initialize());
app.use(passport.session());
io.use(
passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'express.sid',
secret: process.env.SESSION_SECRET,
store: store,
success: onAuthorizeSuccess,
fail: onAuthorizeFail
})
);
myDB(async (client) => {
const myDataBase = await client.db('database').collection('users');
routes(app, myDataBase);
auth(app, myDataBase);
let currentUsers = 0;
io.on('connection', (socket) => {
++currentUsers;
io.emit('user count', currentUsers);
console.log('user ' + socket.request.user.username + ' connected');
socket.on('disconnect', () => {
console.log('A user has disconnected');
--currentUsers;
io.emit('user count', currentUsers);
});
});
}).catch((e) => {
app.route('/').get((req, res) => {
res.render('pug', { title: e, message: 'Unable to login' });
});
});
function onAuthorizeSuccess(data, accept) {
console.log('successful connection to socket.io');
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept) {
if (error) throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
}
http.listen(process.env.PORT || 3000, () => {
console.log('Listening on port ' + process.env.PORT);
});
@shugyoza
Copy link

const MongoStore = require('connect-mongo')(session);
no longer works with current version.

@jamesnascimento1994
Copy link

I just tried a different dependency called 'connect-mongodb-session' and it worked. You can view it here: https://www.npmjs.com/package/connect-mongodb-session

@xondoi
Copy link

xondoi commented Jan 27, 2022

passport.socketio is deprecated

@xondoi
Copy link

xondoi commented Jan 27, 2022

how to pass the tests since this dependency cannot be installed?

@muhammedctgr
Copy link

says passport.socketio is deprecated...no way we gon pass this test without this because we're using it for authorization.
also despite adding cookie-parser as a dependency its failing it..
anyone figured out a way to pass this?

@muhammedctgr
Copy link

and my port is listening on an undefined port...how do I fix pls?
my configuration of the port seems correct

@jamesnascimento1994
Copy link

Has anyone tried: https://www.npmjs.com/package/passport-jwt.socketio, as a replacement for 'passport.socketio'? This one is not deprecated. 6ix-Ville, can you show us your code so we can see what your server looks like?

@muhammedctgr
Copy link

passed the test with passportSocketIo still in my code...dont know why this worked. but my port is still undefined despite using this
http.listen(process.env.PORT || 3000, () => { console.log('Listening on port ' + process.env.PORT); });

@jamesnascimento1994
Copy link

So, I just looked at what I had in my replit file for when I solved these challenges and for my PORT server, I have:
const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log('Listening on port ' + PORT); });

@muhammedctgr
Copy link

says listening on port 3000...but i really appreciate your reply

@andikabhaskara
Copy link

andikabhaskara commented Feb 16, 2022

@6ix-Ville I think that is already working fine, try to register / log in into your website, does it says "user <"username"> attempted to log in." ?

@Ankeet-Ak
Copy link

Below is my server.js code and I'm getting this error: Error connecting to db: connect ECONNREFUSED 127.0.0.1:27017. Can anybody please help me out! Thanks for helping!

'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');

const session = require('express-session');
const passport = require('passport');
const routes = require('./routes.js');
const auth = require('./auth.js');

const app = express();
app.set('view engine', 'pug');

const http = require('http').createServer(app);
const io = require('socket.io')(http);
const passportSocketIo = require('passport.socketio');
const cookieParser = require('cookie-parser');
const MongoStore = require('connect-mongodb-session')(session);
const URI = process.env.MONGO_URI;
const store = new MongoStore({ url: URI });

fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: {secure: false},
key: 'express.sid',
store: store
}));
app.use(passport.initialize());
app.use(passport.session());

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

myDB(async client => {
const myDataBase = await client.db('AdvancedNodeandExpress').collection('users');
routes(app, myDataBase);
auth(app, myDataBase);
let currentUsers = 0;
io.on('connection', socket => {
++currentUsers;
io.emit('user count', currentUsers);
console.log('user' + socket.request.user.username +
' connected'
);
socket.on('disconnect', () => {
--currentUsers;
console.log('A user has disconnected!');
io.emit('user count', cuurentUsers);
});
});
}).catch((e) => {
app.route('/').get((req, res) => {
res.render('pug', {title: e, message: 'Unable to login'});
});
});

function onAuthorizeSuccess(data, accept) {
console.log('successful connection to socket.io');
accept(null, true);
}

function onAuthorizeFail(data, message, error, accept) {
if (error) throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
}

const PORT = process.env.PORT || 3000;
http.listen(PORT, () => {
console.log('Listening on port ' + PORT);
});

@muhammedctgr
Copy link

muhammedctgr commented Mar 8, 2022

Your database connection is not set up well..more over, have you defined your database in your secret environment?

@Ankeet-Ak
Copy link

Your database connection is not set up well..more over, have you defined your database in your secret environment?

But I was able to login in my previous tests! And I can also see documents in my database here in Atlas where FCC login credentials are also there.
username:"freeCodeCampTester1646219062494"
password:"freeCodeCampTester1646219062494"

@muhammedctgr
Copy link

Did you see other credentials in ur database aside FCC's?
Make sure your database is poperly set up with variable MONGO_URI in sec env...ds should be familiar.
Screenshot_20220308-100725
Change the highlighted area to 'database'

@muhammedctgr
Copy link

muhammedctgr commented Mar 8, 2022

Always put your codes in btw 2 backticks ( )so its easier to read.

@dwisatriow
Copy link

@Ankeet-Ak Also try to fix cuurentUsers typo on line 63 of your server.js

@Ankeet-Ak
Copy link

@6ix-Ville But my database name is 'AdvanceNodeandExpress' and even if I change it to 'database' it still shows the same error.
Github_Advanced_Node_and_Express

Session_Secret

Actually, I'm completely beginner to creating db like this as in the last course 'Backend Development and API' we were not taught creating db like this. So, can you please give some references on how to create database like here.

@dwisatriow thanks for your help! After correcting the typo, the page loaded but again it was unable to access db!

@AyobamiMichael
Copy link

Has anyone tried: https://www.npmjs.com/package/passport-jwt.socketio, as a replacement for 'passport.socketio'? This one is not deprecated. 6ix-Ville, can you show us your code so we can see what your server looks like?

Yes I tried it, it not working

@muhammedctgr
Copy link

passport.socketio still works for me

@cherylli
Copy link

how to pass the tests since this dependency cannot be installed?

Make sure you use the versions specified. i.e. passport.socketio@~3.7.0, connect-mongo@~3.2.0, and cookie-parser@~1.4.5
till they update the material and tests.

@Freel11
Copy link

Freel11 commented Jul 28, 2022

I just tried a different dependency called 'connect-mongodb-session' and it worked. You can view it here: https://www.npmjs.com/package/connect-mongodb-session

worked for me. Just remember to access user name like this -> socket.request.user.username instead of -> socket.request.user.name.

@wdramsey
Copy link

Use this process if you want to still use connect-mongo: https://stackoverflow.com/questions/66654037/mongo-connect-error-with-mongo-connectsession. And use this process to replace passport-socket.io since it is deprecated: https://github.com/jfromaniello/passport.socketio/issues/148.

@ArtitRise
Copy link

Still not passed the test.
Please recommend.
Below is my server.js.

'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const session = require('express-session');
const passport = require('passport');
const routes = require('./routes');
const auth = require('./auth.js');

const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const passportSocketIo = require('passport.socketio');
const cookieParser = require('cookie-parser');
var MongoStore = require('connect-mongodb-session')(session);
const URI = process.env.MONGO_URI;
const store = new MongoStore({ url: URI });

app.set('view engine', 'pug');

fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { secure: false },
key: 'express.sid',
store: store
}));

app.use(passport.initialize());
app.use(passport.session());

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

myDB(async (client) => {
const myDataBase = await client.db('database').collection('users');

routes(app, myDataBase);
auth(app, myDataBase);

let currentUsers = 0;
io.on('connection', (socket) => {
++currentUsers;
io.emit('user count', currentUsers);
console.log('user ' + socket.request.user.username + ' connected');

socket.on('disconnect', () => {
  console.log('A user has disconnected');
  --currentUsers;
  io.emit('user count', currentUsers);
});

});
}).catch((e) => {
app.route('/').get((req, res) => {
res.render('pug', { title: e, message: 'Unable to login' });
});
});

function onAuthorizeSuccess(data, accept) {
console.log('successful connection to socket.io');

accept(null, true);
}

function onAuthorizeFail(data, message, error, accept) {
if (error) throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
}

http.listen(process.env.PORT || 3000, () => {
console.log('Listening on port ' + process.env.PORT);
});

@wdramsey
Copy link

Try using connect-mongo using the method I linked above: https://stackoverflow.com/questions/66654037/mongo-connect-error-with-mongo-connectsession. You need to use this syntax for declaration: const MongoDBStore = require('connect-mongo'); const URI = process.env.MONGO_URI; const store = MongoDBStore.create({ mongoUrl: URI });

I am not sure if passport-socket.io will work for you as it did not for my set up so I suggest using this method to replace it: https://github.com/jfromaniello/passport.socketio/issues/148. Your tests may not even pass but if you run it, it should work perfectly fine if you follow those links.

@ArtitRise
Copy link

Thank you.

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