authentication.js 1.24 KB
Newer Older
1
/* global WIKI */
2 3 4 5 6 7

// ------------------------------------
// Google ID Account
// ------------------------------------

const GoogleStrategy = require('passport-google-oauth20').Strategy
Nick's avatar
Nick committed
8
const _ = require('lodash')
9

10 11
module.exports = {
  init (passport, conf) {
12 13 14 15 16 17 18 19 20
    const strategy = new GoogleStrategy({
      clientID: conf.clientId,
      clientSecret: conf.clientSecret,
      callbackURL: conf.callbackURL,
      passReqToCallback: true
    }, async (req, accessToken, refreshToken, profile, cb) => {
      try {
        if (conf.hostedDomain && conf.hostedDomain != profile._json.hd) {
          throw new Error('Google authentication should have been performed with domain ' + conf.hostedDomain)
Nick's avatar
Nick committed
21
        }
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
        const user = await WIKI.models.users.processProfile({
          providerKey: req.params.strategy,
          profile: {
            ...profile,
            picture: _.get(profile, 'photos[0].value', '')
          }
        })
        cb(null, user)
      } catch (err) {
        cb(err, null)
      }
    })

    if (conf.hostedDomain) {
      strategy.authorizationParams = function(options) {
        return {
          hd: conf.hostedDomain
        }
      }
    }

43
    passport.use(conf.key, strategy)
44 45 46
  },
  logout (conf) {
    return '/'
47
  }
48
}