add Google auth plugin

This commit is contained in:
Kit Westneat
2018-02-16 18:17:34 -05:00
parent 26476f42f7
commit 499a7fe686
17 changed files with 241 additions and 1 deletions
@@ -0,0 +1,41 @@
const GoogleStrategy = require('passport-google-oauth2').Strategy;
const UsersService = require('services/users');
const { ValidateUserLogin } = require('services/passport');
let { ROOT_URL } = require('config');
if (ROOT_URL[ROOT_URL.length - 1] !== '/') {
ROOT_URL += '/';
}
module.exports = passport => {
if (
process.env.TALK_GOOGLE_CLIENT_ID &&
process.env.TALK_GOOGLE_CLIENT_SECRET &&
process.env.TALK_ROOT_URL
) {
passport.use(
new GoogleStrategy(
{
clientID: process.env.TALK_GOOGLE_CLIENT_ID,
clientSecret: process.env.TALK_GOOGLE_CLIENT_SECRET,
callbackURL: `${ROOT_URL}api/v1/auth/google/callback`,
passReqToCallback: true,
},
async (req, accessToken, refreshToken, profile, done) => {
let user;
try {
user = await UsersService.findOrCreateExternalUser(profile);
} catch (err) {
return done(err.toString());
}
return ValidateUserLogin(profile, user, done);
}
)
);
} else if (process.env.NODE_ENV !== 'test') {
throw new Error(
'Google cannot be enabled, missing one of TALK_GOOGLE_CLIENT_ID, TALK_GOOGLE_CLIENT_SECRET, TALK_ROOT_URL'
);
}
};
@@ -0,0 +1,29 @@
module.exports = router => {
const { passport, HandleAuthPopupCallback } = require('services/passport');
/**
* Google auth endpoint, this will redirect the user immediatly to google
* for authorization.
*/
router.get(
'/api/v1/auth/google',
passport.authenticate('google', {
display: 'popup',
authType: 'rerequest',
scope: ['profile'],
})
);
/**
* Google callback endpoint, this will send the user a html page designed to
* send back the user credentials upon sucesfull login.
*/
router.get('/api/v1/auth/google/callback', (req, res, next) => {
// Perform the google login flow and pass the data back through the opener.
passport.authenticate(
'google',
{ session: false },
HandleAuthPopupCallback(req, res, next)
)(req, res, next);
});
};