authentication.js 2.35 KB
Newer Older
1 2 3 4 5
const _ = require('lodash')

/* global WIKI */

// ------------------------------------
NGPixel's avatar
NGPixel committed
6
// OAuth2 Account
7 8 9 10 11 12 13 14 15 16 17 18 19
// ------------------------------------

const OAuth2Strategy = require('passport-oauth2').Strategy

module.exports = {
  init (passport, conf) {
    var client = new OAuth2Strategy({
      authorizationURL: conf.authorizationURL,
      tokenURL: conf.tokenURL,
      clientID: conf.clientId,
      clientSecret: conf.clientSecret,
      userInfoURL: conf.userInfoURL,
      callbackURL: conf.callbackURL,
20
      passReqToCallback: true,
21
      scope: conf.scope,
22
      state: conf.enableCSRFProtection
23 24 25 26 27 28
    }, async (req, accessToken, refreshToken, profile, cb) => {
      try {
        const user = await WIKI.models.users.processProfile({
          providerKey: req.params.strategy,
          profile: {
            ...profile,
NGPixel's avatar
NGPixel committed
29 30
            id: _.get(profile, conf.userIdClaim),
            displayName: _.get(profile, conf.displayNameClaim, '???'),
31 32 33
            email: _.get(profile, conf.emailClaim)
          }
        })
34 35 36 37 38 39 40 41 42 43 44 45 46
        if (conf.mapGroups) {
          const groups = _.get(profile, conf.groupsClaim)
          if (groups && _.isArray(groups)) {
            const currentGroups = (await user.$relatedQuery('groups').select('groups.id')).map(g => g.id)
            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)) {
              await user.$relatedQuery('groups').unrelate().where('groupId', groupId)
            }
          }
        }
47 48 49 50 51 52 53
        cb(null, user)
      } catch (err) {
        cb(err, null)
      }
    })

    client.userProfile = function (accesstoken, done) {
54
      this._oauth2._useAuthorizationHeaderForGET = !conf.useQueryStringForAccessToken
55 56 57 58 59 60
      this._oauth2.get(conf.userInfoURL, accesstoken, (err, data) => {
        if (err) {
          return done(err)
        }
        try {
          data = JSON.parse(data)
NGPixel's avatar
NGPixel committed
61
        } catch (e) {
62 63 64 65 66
          return done(e)
        }
        done(null, data)
      })
    }
67
    passport.use(conf.key, client)
NGPixel's avatar
NGPixel committed
68 69 70 71 72 73 74
  },
  logout (conf) {
    if (!conf.logoutURL) {
      return '/'
    } else {
      return conf.logoutURL
    }
75 76
  }
}