req.user is unidentified in session (Node, express, session, passport) Ask Question

For some reason req.user is undefined, and after 4+ hours of trying to figure out why, I’m asking here. I even copy-pasted the server/index.js file of a friend’s server, changed the auth strategy so it worked for mine, and I get the same issue.

Everything else is working. It redirects to auth0, comes back to the correct place, either creates a new user in the DB or finds the user. In passport.serializeUser it has all the data I passed along. But when I hit the ‘/auth/me’ endpoint, req.user is undefined.

server/index.js

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
const session = require("express-session");
const passport = require('passport');
const Auth0Strategy = require('passport-auth0');
const massive = require('massive');
const axios = require('axios');
const process = require("process");
const moment = require('moment');

const app = express();

//app.use(express.static(__dirname + './../build'));
app.use(bodyParser.json());
app.use(cors());

app.use(session({
    secret: process.env.SECRET, 
    cookie: { maxAge: 60000 },
    resave: false,
    saveUninitialized: true
   }));
app.use(passport.initialize());
app.use(passport.session()); 

// Use the session middleware
massive(process.env.CONNECTION_STRING)
.then( (db) => {
    console.log('Connected to Heroku')
    app.set('db', db);
}).catch(err=>console.log(err))
 


passport.use(new Auth0Strategy({
    domain: process.env.AUTH_DOMAIN,
    clientID: process.env.AUTH_CLIENT_ID,
    clientSecret: process.env.AUTH_CLIENT_SECRET,
    callbackURL: process.env.AUTH_CALLBACK
}, (accessToken, refreshToken, extraParams, profile, done) => {
    const db = app.get("db");
    const userData = profile._json;

    db.find_user([userData.identities[0].user_id]).then(user => {
    if (user[0]) {
        return done(null, user[0]);
    } else {
        db.create_user([
            userData.given_name,
            userData.family_name,
            userData.email,
            userData.identities[0].user_id
        ])
        .then(user => {
            return done(null, user);
        });
    }
    });
}))

passport.serializeUser( (user, done) => {
    //console.log('serializeuser', user)
    done(null, user);
}) 

passport.deserializeUser( (id, done) => {
    app.get("db").find_session_user([id])
        .then(user => {
        console.log(user);
        done(null, user[0]);
        });
})

app.get('/auth', passport.authenticate('auth0'));
app.get('/auth/callback', passport.authenticate('auth0', {
    successRedirect: process.env.SUCCESS_REDIRECT
}))

app.get('/auth/me', (req, res) => {
    console.log('auth/me endpoint hit')
    console.log(req.user)
    if(!req.user){
        return res.status(401).send('No user logged in.');
    }
    return res.status(200).send(req.user);
})

app.listen(process.env.PORT, () => console.log(`Listening on port: ${process.env.PORT}`));

One thought on “req.user is unidentified in session (Node, express, session, passport) Ask Question”

Leave a Reply

Your email address will not be published. Required fields are marked *