Skip to content

Instantly share code, notes, and snippets.

@circa10a
Created July 5, 2019 05:31
Show Gist options
  • Save circa10a/c99862c33d62001b1a3c9517c9ab8d3b to your computer and use it in GitHub Desktop.
Save circa10a/c99862c33d62001b1a3c9517c9ab8d3b to your computer and use it in GitHub Desktop.
github oauth2 with express and sessions
const express = require('express')
const passport = require('passport');
const session = require('express-session');
const app = express()
app.use(session({secret: "soeffingsecret"}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
const GitHubStrategy = require('passport-github').Strategy;
passport.use(new GitHubStrategy({
clientID: 'blah',
clientSecret: 'blah',
callbackURL: "http://127.0.0.1:3000/auth/github/callback"
},
function(accessToken, refreshToken, profile, cb) {
console.log(`Access Token: ${accessToken}`)
console.log(`Refresh Token: ${refreshToken}`)
console.log(`Profile: ${JSON.stringify(profile)}`)
profileData = profile;
return cb(null, profile)
}
));
app.set('view engine', 'pug')
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
app.get('/auth/github', passport.authenticate('github'));
// GitHub will call this URL
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/' }),
function(req, res) {
res.redirect('/success');
});
app.get('/success', function (req, res) {
console.log(req.isAuthenticated())
console.log(req.user)
res.render('success', { title: 'Hey', message: 'youre in', profileData: JSON.stringify(req.user, null, 4) })
})
app.listen(3000, () => {
console.log('listening on 3000')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment