FCC Advanced Node and Express SocketIo

Hello;
I have a strange thing where my GitHub strategy works to login, but when it redirects, it seems to fail and pump me back to “/” instead of “/chat”

I console log out the profile from github so for sure git hub has logged me in and sent back my profile, but somehow I can’t get past the redirect to get to /chat:

Any ideas what is causing it to fail(the code is passing the tests, but my app isn’t redirecting to “/chat”)…perhaps something to do with session?

Any ideas?

Same problem with the previous challenge : local strategy, passes tests, but the login redirect fails to show the logged in page…
my app: https://boilerplate-socketio.pauloconnell.repl.co/

My Routes.js:

const passport    = require('passport');

module.exports = function (app, db) {
  
    function ensureAuthenticated(req, res, next) {
      if (req.isAuthenticated()) {
          return next();
      }
      console.log("authentication failed")
      res.redirect('/');
    };

    app.route('/auth/github')
      .get(passport.authenticate('github'));

    app.route('/auth/github/callback')
      .get(passport.authenticate('github', { failureRedirect: '/' }), (req,res) => {
         // req.session.user_id = req.user.id;
          res.redirect("/chat");
      });

    app.route('/')
      .get((req, res) => {
        res.render(process.cwd() + '/views/pug/index');
      });

    app.route('/chat')
      .get(ensureAuthenticated, (req, res) => {
       // console.log(req.session);
           res.render(process.cwd() + '/views/pug/chat', {user: req.user});
      });

    app.route('/logout')
      .get((req, res) => {
          req.logout();
          res.redirect('/');
      });

    app.use((req, res, next) => {
      res.status(404)
        .type('text')
        .send('Not Found');
    });
  
}

and this is my server.js:

'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 passport    = require('passport');
const cookieParser= require('cookie-parser')
const app         = express();
const http        = require('http').Server(app);
const sessionStore= new session.MemoryStore();
const io          =require('socket.io')(http);
const passportSocketIo=require('passport.socketio');
const cors = require('cors');
app.use(cors());
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);
    }else{

  
    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 => {
  console.log('A user has connected');
  ++currentUsers;
  //io.emit('user count', currentUsers);
  io.emit("user", {name:socket.request.user.name, currentUsers, connected:true});

  socket.on('chat message', (message)=>{
    io.emit('chat message', {name: socket.request.user.name, message});
  });

  socket.on('disconnect', () => { /*anything you want to do on disconnect*/
    console.log('a user had disconnected');
    --currentUsers;
    io.emit('user count', {name: socket.request.user.name, currentUsers, connected: false});
  });


  });

  }
  
//  defined in ROUTES.js app.route('/auth/github')
//         .get(passport.authenticate('github'));
      
//   app.route('/auth/github/callback')
//         .get(passport.authenticate('github', {failureRedirect:'/'}), (req,res)=>{
//           res.redirect('/profile');
//         });
//     //end socket.io code
  
  
});

Does req.isAuthenticated() return true?

Does the client have a cookie with the session id? You can use dev tools in the browser to see your cookies and you can check that way.

I’m not sure with non-local passport stuff how sessions are stored, but if the session is stored in some datastore that you have access to, make sure that the session is being saved there?

Hey Marius;
I can’t seem to get req.isAuthenticated()…it seems I get an error before my console.log

But I can console log out the user profile, so I’m sure I’m getting the profile, will keep hunting…

I noticed a sneaky error in the console that seems to be the cuprit:

[Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIContentSniffer.getMIMETypeFromContent]"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: resource:///modules/FaviconLoader.jsm :: onStopRequest :: line 284"  data: no] FaviconLoader.jsm:284:24
    onStopRequest resource:///modules/FaviconLoader.jsm:284
    AsyncFunctionNext self-hosted:684

Hey paul.

If you have not resolved this here are two things to help:

  1. The PIP browser in Repl.it does not persist the session data. So, you need to test using the full preview of your app.
  2. If you are encountering any more issues, this whole section has been re-written, and will be available on the production environment soon. This will include a new boilerplate. So, if you are still busy with this section by then, you may need to restart, to ensure the tests pass. One of the major changes is the same boilerplate is used throughout the section

Cheers

THanks again Sky!

I was actually able to pass all the tests, and recieve my profile from gitHub, but not able to get past the error to be logged into the chat room…

Just to be sure, the full preview of my app is deployed by clicking here right? (labeled link ‘FULL’- on right hand side)

Yes, correct. :+1:

Well done, on passing the tests.