Skip to content

Instantly share code, notes, and snippets.

@lukebyrne
Created October 18, 2018 04:24
Show Gist options
  • Save lukebyrne/fbee330ca515604391e58cdbac7a1586 to your computer and use it in GitHub Desktop.
Save lukebyrne/fbee330ca515604391e58cdbac7a1586 to your computer and use it in GitHub Desktop.
require('dotenv').config()
const cors = require('cors')
const bodyParser = require('body-parser')
const express = require('express')
const expressJwt = require('express-jwt')
const cookieSession = require('cookie-session')
const jwt = require('jsonwebtoken')
const passport = require('passport')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const jwtSecret = Buffer.from('Zn8Q5tyZ/G1MHltc4F/gTkVJMlrbKiZt', 'base64')
var knex = require('knex')({
client: 'pg',
connection: process.env.TWIGGY_DB
})
passport.serializeUser((user, done) => {
done(null, user)
})
passport.deserializeUser((user, done) => {
knex('users')
.where({email: user.email})
.first('email')
.returning(['id', 'email']).then((user) => {
done(null, user)
})
})
// Setup Passport
passport.use(
new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/redirect'
}, (accessToken, refreshToken, profile, done) => {
const email = profile.emails[0].value
knex('users').where({email: email}).then((user) => {
// !currentUser, pass it on
if(user){
console.log('currentUser is: ', user[0]);
done(null, user[0]);
} else {
// !currentUser, create user in our db
knex('users')
.insert({
email: email,
})
.returning(['id', 'email'])
.then((user) => {
console.log('newUser: ', user[0])
done(null, user[0])
})
}
})
})
)
// Setup app
const app = express()
app.use(cors(), bodyParser.json(), expressJwt({
secret: jwtSecret,
credentialsRequired: false
}))
// set up session cookies
app.use(cookieSession({
// Lasts one day
maxAge: 24 * 60 * 60 * 1000,
// @todo needs a better cookieKey
keys: [process.env.SESSION_COOKIE_KEY]
}))
app.use(passport.initialize())
app.use(passport.session())
app.get('/', (req, res) => {
res.send('oauth2')
})
app.get('/oauth2', passport.authenticate('google', {
scope: ['profile', 'email'],
hostedDomain: process.env.HOSTED_DOMAIN
}))
app.get('/redirect', passport.authenticate('google'), (req, res) => {
const token = jwt.sign({sub: req.user.email}, jwtSecret)
res.redirect(`${process.env.REDIRECT_URL}?token=${token}`)
})
app.get('/logout', (req, res) => {
req.logout()
res.redirect('/')
})
app.listen(3000, () => {
console.log('app now listening for requests on port 3000')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment