2020-04-13 07:34:44 -04:00
|
|
|
import { Router } from 'express'
|
|
|
|
import passport from 'passport'
|
2020-04-13 07:52:44 -04:00
|
|
|
import * as Google from 'passport-google-oauth20'
|
2020-04-13 09:23:11 -04:00
|
|
|
import { config } from '../../../config'
|
|
|
|
import { AuthMiddleware } from '../interface'
|
2020-04-13 07:34:44 -04:00
|
|
|
import { passportGeneralCallback } from '../utils'
|
|
|
|
|
|
|
|
const googleAuth = Router()
|
|
|
|
|
|
|
|
export const GoogleMiddleware: AuthMiddleware = {
|
2020-04-13 09:23:11 -04:00
|
|
|
getMiddleware: function (): Router {
|
2020-04-13 07:52:44 -04:00
|
|
|
passport.use(new Google.Strategy({
|
2020-04-13 07:34:44 -04:00
|
|
|
clientID: config.google.clientID,
|
|
|
|
clientSecret: config.google.clientSecret,
|
|
|
|
callbackURL: config.serverURL + '/auth/google/callback',
|
|
|
|
userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo'
|
2020-04-13 09:23:11 -04:00
|
|
|
}, (
|
|
|
|
accessToken: string,
|
|
|
|
refreshToken: string,
|
|
|
|
profile: any,
|
|
|
|
done) => {
|
|
|
|
/*
|
|
|
|
This ugly hack is neccessary, because the Google Strategy wants a done-callback with an err as Error | null | undefined
|
|
|
|
but the passportGeneralCallback (and every other PassportStrategy) want a done-callback with err as string | Error | undefined
|
|
|
|
Note the absence of null. The lambda converts all `null` to `undefined`.
|
|
|
|
*/
|
|
|
|
passportGeneralCallback(accessToken, refreshToken, profile, (err?, user?) => {
|
|
|
|
done(err === null ? undefined : err, user)
|
|
|
|
})
|
|
|
|
}))
|
2020-04-13 07:34:44 -04:00
|
|
|
|
|
|
|
googleAuth.get('/auth/google', function (req, res, next) {
|
2020-04-13 07:52:44 -04:00
|
|
|
const authOpts = { scope: ['profile'], hostedDomain: config.google.hostedDomain }
|
2020-04-13 07:34:44 -04:00
|
|
|
passport.authenticate('google', authOpts)(req, res, next)
|
|
|
|
})
|
|
|
|
googleAuth.get('/auth/google/callback',
|
|
|
|
passport.authenticate('google', {
|
|
|
|
successReturnToOrRedirect: config.serverURL + '/',
|
|
|
|
failureRedirect: config.serverURL + '/'
|
|
|
|
})
|
|
|
|
)
|
|
|
|
return googleAuth
|
|
|
|
}
|
|
|
|
}
|