Last active
October 17, 2022 13:52
-
-
Save ShaunSHamilton/c9dd9ab5275b9739f1bf299cee86f5ec to your computer and use it in GitHub Desktop.
Advanced Node and Express - Implement the Serialization of a Passport User
This file contains hidden or 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'); | |
const app = express(); | |
app.set('view engine', 'pug'); | |
app.set('views', './views/pug'); | |
app.use(session({ | |
secret: process.env.SESSION_SECRET, | |
resave: true, | |
saveUninitialized: true, | |
cookie: { secure: false } | |
})); | |
app.use(passport.initialize()); | |
app.use(passport.session()); | |
fccTesting(app); // For fCC testing purposes | |
app.use('/public', express.static(process.cwd() + '/public')); | |
app.use(express.json()); | |
app.use(express.urlencoded({ extended: true })); | |
myDB(async client => { | |
const myDataBase = await client.db('database').collection('users'); | |
app.route('/').get((req, res) => { | |
res.render('index', { | |
title: 'Connected to Database', | |
message: 'Please log in' | |
}); | |
}); | |
passport.serializeUser((user, done) => { | |
done(null, user._id); | |
}); | |
passport.deserializeUser((id, done) => { | |
myDataBase.findOne({ _id: new ObjectID(id) }, (err, doc) => { | |
done(null, doc); | |
}); | |
}); | |
}).catch(e => { | |
app.route('/').get((req, res) => { | |
res.render('index', { title: e, message: 'Unable to connect to database' }); | |
}); | |
}); | |
const PORT = process.env.PORT || 3000; | |
app.listen(PORT, () => { | |
console.log(`Listening on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment