Created
July 5, 2019 05:31
-
-
Save circa10a/c99862c33d62001b1a3c9517c9ab8d3b to your computer and use it in GitHub Desktop.
github oauth2 with express and sessions
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
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