Created
October 26, 2017 20:24
-
-
Save jwo/ea79620b5229e7821e4ae61055899cf9 to your computer and use it in GitHub Desktop.
Simple way to sign in with github for oAuth in Node/Express
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 app = express() | |
var passport = require("passport") | |
var session = require("express-session") | |
var GitHubStrategy = require("passport-github2").Strategy | |
const GITHUB_CLIENT_ID = "your-client-id-here" // or get from process.env.GITHUB_CLIENT_ID | |
const GITHUB_CLIENT_SECRET = "your-client-secret-here" // or get from process.env.GITHUB_CLIENT_SECRET | |
const GITHUB_CALLBACK_URL = "http://localhost:5000/auth/github/callback" // or get from process.env.GITHUB_CALLBACK_URL | |
function ensureAuthenticated(req, res, next) { | |
if (req.isAuthenticated()) { | |
return next() | |
} | |
res.redirect("/login") | |
} | |
passport.serializeUser(function(user, done) { | |
done(null, user) | |
}) | |
passport.deserializeUser(function(obj, done) { | |
done(null, obj) | |
}) | |
passport.use( | |
new GitHubStrategy( | |
{ | |
clientID: GITHUB_CLIENT_ID, | |
clientSecret: GITHUB_CLIENT_SECRET, | |
callbackURL: GITHUB_CALLBACK_URL | |
}, | |
function(accessToken, refreshToken, profile, done) { | |
// asynchronous verification, for effect... | |
console.log({ accessToken, refreshToken, profile }) | |
// an example of how you might save a user | |
// new User({ username: profile.username }).fetch().then(user => { | |
// if (!user) { | |
// user = User.forge({ username: profile.username }) | |
// } | |
// | |
// user.save({ profile: profile, access_token: accessToken }).then(() => { | |
// return done(null, user) | |
// }) | |
// }) | |
} | |
) | |
) | |
app.use( | |
session({ secret: "keyboard cat", resave: false, saveUninitialized: false }) | |
) | |
app.use(passport.initialize()) | |
app.use(passport.session()) | |
app.get("/", (req, res) => { | |
res.send("<a href='/secret'>Access Secret Area</a>") | |
}) | |
app.get("/login", (req, res) => { | |
res.send("<a href='/auth/github'>Sign in With GitHub</a>") | |
}) | |
app.get("/secret", ensureAuthenticated, (req, res) => { | |
res.send(`<h2>yo ${req.user}</h2>`) | |
}) | |
app.get( | |
"/auth/github", | |
passport.authenticate("github", { scope: ["repo:status"] }), /// Note the scope here | |
function(req, res) { } | |
) | |
app.get( | |
"/auth/github/callback", | |
passport.authenticate("github", { failureRedirect: "/login" }), | |
function(req, res) { | |
res.redirect("/") | |
} | |
) | |
const port = process.env.PORT || 5000 | |
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