authentication.js 2.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
const _ = require('lodash')

/* global WIKI */

// ------------------------------------
// OpenID Connect Account
// ------------------------------------

const OpenIDConnectStrategy = require('passport-openidconnect').Strategy

module.exports = {
  init (passport, conf) {
13
    passport.use(conf.key,
14 15 16 17 18 19
      new OpenIDConnectStrategy({
        authorizationURL: conf.authorizationURL,
        tokenURL: conf.tokenURL,
        clientID: conf.clientId,
        clientSecret: conf.clientSecret,
        issuer: conf.issuer,
20
        userInfoURL: conf.userInfoURL,
21 22
        callbackURL: conf.callbackURL,
        passReqToCallback: true
23 24 25
      }, async (req, iss, uiProfile, idProfile, context, idToken, accessToken, refreshToken, params, cb) => {
        const profile = Object.assign({}, idProfile, uiProfile)

26 27
        try {
          const user = await WIKI.models.users.processProfile({
28
            providerKey: req.params.strategy,
29 30
            profile: {
              ...profile,
31
              email: _.get(profile, '_json.' + conf.emailClaim),
32
              displayName: _.get(profile, '_json.' + conf.displayNameClaim, '')
33
            }
34
          })
35 36
          if (conf.mapGroups) {
            const groups = _.get(profile, '_json.' + conf.groupsClaim)
37
            if (groups && _.isArray(groups)) {
38
              const currentGroups = (await user.$relatedQuery('groups').select('groups.id')).map(g => g.id)
39 40 41 42 43
              const expectedGroups = Object.values(WIKI.auth.groups).filter(g => groups.includes(g.name)).map(g => g.id)
              for (const groupId of _.difference(expectedGroups, currentGroups)) {
                await user.$relatedQuery('groups').relate(groupId)
              }
              for (const groupId of _.difference(currentGroups, expectedGroups)) {
44
                await user.$relatedQuery('groups').unrelate().where('groupId', groupId)
45 46 47
              }
            }
          }
48
          cb(null, user)
49
        } catch (err) {
50 51
          cb(err, null)
        }
52 53
      })
    )
54 55 56 57 58 59 60
  },
  logout (conf) {
    if (!conf.logoutURL) {
      return '/'
    } else {
      return conf.logoutURL
    }
61 62
  }
}