Issue: Authentication with Socket.IO

Affected page

challenge link

Your code

'use strict';
require('dotenv').config();
const express = require('express');
let myDB = require('./connection');
const session = require('express-session')
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const passport = require('passport')
const auth = require('./auth.js')
const routes = require('./routes.js')
const MongoStore = require('connect-mongo')(session);
const URI = process.env.MONGO_URI;
const store = new MongoStore({ url: URI });
const passportSocketIo = require("passport.socketio");



const app = express();

const http = require('http').createServer(app);
const io = require('socket.io')(http);

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 }
}));

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



myDB(async (client) => {
  const myDataBase = await client.db('repl').collection('users');
  let currentUsers = 0;
  io.on('connection', socket => {
    console.log('A user has connected');
    ++currentUsers;
    io.emit('user count', currentUsers);
  });
  socket.on('disconnect', () => {
    /*anything you want to do on disconnect*/
    --currentUsers;
  });
  routes(app, myDataBase);
  auth(app, myDataBase);

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


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

Expected behavior

image
I’ve written above as mentioned in challenge description.

Screenshots

image
But the code shared in description is not working as it should.

System

  • Device: laptop
  • OS: ubuntu 20.04
  • Browser: firefox
  • Version: 92.0 (64-bit)

Additional context

I’m doing above challenge in repl

This might be caused by the used version of connect-mongo. Have you tried using 3.2.0 as in the challenge description?

Even after changing mongo-connect to 3.2.0. It is not working.
I was able to achieve same functionality wil latest mongo-connect version.

image

I’ve forked your code, and after adding required environment variables in the Secrets tab, all challenge tests are passing for me.

for me socket.request.user.name is undefined.
that is because onAuthorizeFail gets called when authenticating with socket.
console.log(socket.request.user) prints { logged_in: false }
My main concern is not about passing test cases rather about actual functionality

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.