-
-
Save camperbot/175f2f585a2d8034044c7e8857d5add7 to your computer and use it in GitHub Desktop.
Advanced Node and Express - Implement the Serialization of a Passport User
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'; | |
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 ObjectID = require('mongodb').ObjectID; | |
const app = express(); | |
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('database').collection('users'); | |
// Be sure to change the title | |
app.route('/').get((req, res) => { | |
// Change the response to render the Pug template | |
res.render('pug', { | |
title: 'Connected to Database', | |
message: 'Please login' | |
}); | |
}); | |
// Serialization and deserialization here... | |
passport.serializeUser((user, done) => { | |
done(null, user._id); | |
}); | |
passport.deserializeUser((id, done) => { | |
myDataBase.findOne({ _id: new ObjectID(id) }, (err, doc) => { | |
done(null, doc); | |
}); | |
}); | |
// Be sure to add this... | |
}).catch((e) => { | |
app.route('/').get((req, res) => { | |
res.render('pug', { title: e, message: 'Unable to login' }); | |
}); | |
}); | |
// app.listen out here... | |
app.listen(process.env.PORT || 3000, () => { | |
console.log('Listening on port ' + process.env.PORT); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you. Refreshing does work, as does opening the app in a separate browser tab. I spent sooo long reconfiguring my code and trying to figure out where I'd made a mistake and it turns out my code was fine all along!