Skip to content

Instantly share code, notes, and snippets.

@lukebyrne
Created October 18, 2018 07:12
Show Gist options
  • Save lukebyrne/72129edfb5ae09c844826f7a32b0f322 to your computer and use it in GitHub Desktop.
Save lukebyrne/72129edfb5ae09c844826f7a32b0f322 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)
})
// 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])
})
}
})
})
)
const app = express()
app.use(passport.initialize())
app.get('/oauth2', passport.authenticate('google', {
scope: ['profile', 'email'],
hostedDomain: process.env.HOSTED_DOMAIN
}))
app.get('/redirect', passport.authenticate('google'), (req, res) => {
const claims = {
sub: req.user.id,
email: req.user.email,
'https://hasura.io/jwt/claims': {
'x-hasura-default-role': 'admin',
'x-hasura-user-id': req.user.id,
'x-hasura-allowed-roles': ['admin','user']
}
}
const token = jwt.sign(claims, jwtSecret)
res.redirect(`${process.env.REDIRECT_URL}?token=${token}`)
})
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