Created
February 17, 2017 13:30
-
-
Save benfletcher/ac6913884ac61dbd9e5389a4e0143efd to your computer and use it in GitHub Desktop.
Passport Google and Bearer Strategy
This file contains hidden or 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
var express = require('express'); | |
var passport = require('passport'); | |
var GoogleStrategy = require('passport-google-oauth20').Strategy; | |
var BearerStrategy = require('passport-http-bearer').Strategy; | |
var app = express(); | |
app.use('/', express.static('build')); | |
passport.use(new GoogleStrategy({ | |
clientID: '43640532528-uhilvmr6bjh6crafbrc40cd9p48juph8.apps.googleusercontent.com', | |
clientSecret: 'K46mFEHNisbU0IY7yqRg5wGL', | |
callbackURL: "http://localhost:3000/auth/google/callback" | |
}, function (accessToken, refreshToken, profile, done) { | |
console.log('=======', accessToken); | |
// Add real find or create here | |
const user = { | |
googleId: profile.id, | |
accessToken: accessToken, | |
displayName: profile.name | |
}; | |
return done(null, user); | |
})); | |
app.get('/auth/google', passport.authenticate('google', { scope: ['profile'] })); | |
app.get('/auth/google/callback', | |
passport.authenticate('google', { failureRedirect: '/login', session: false }), | |
function (req, res) { | |
res.cookie('accessToken', req.user.accessToken, { expires: 0 }); | |
res.redirect('/quiz'); | |
}); | |
app.get('/auth/logout', function (req, res) { | |
req.logout(); | |
res.redirect('/home'); | |
}); | |
passport.use(new BearerStrategy( | |
function (accessToken, done) { | |
console.log('token', accessToken); | |
User.findOne({ accessToken: accessToken }) | |
.then(user => { | |
return done(null, user, { scope: 'read' }); | |
}) | |
} | |
)); | |
app.get('/api/questions', passport.authenticate('bearer', { session: false }), | |
function (req, res) { | |
res.json({ | |
message: 'respond with list of questions' | |
}) | |
}); | |
app.listen(3000, function () { | |
console.log('Listening at 3000!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment