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

/* global WIKI */

// ------------------------------------
// SAML Account
// ------------------------------------

const SAMLStrategy = require('passport-saml').Strategy

module.exports = {
  init (passport, conf) {
Nick's avatar
Nick committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    let samlConfig = {
      callbackUrl: conf.callbackURL,
      entryPoint: conf.entryPoint,
      issuer: conf.issuer,
      signatureAlgorithm: conf.signatureAlgorithm,
      identifierFormat: conf.identifierFormat,
      acceptedClockSkewMs: _.toSafeInteger(conf.acceptedClockSkewMs),
      disableRequestedAuthnContext: conf.disableRequestedAuthnContext,
      authnContext: conf.authnContext,
      forceAuthn: conf.forceAuthn,
      providerName: conf.providerName,
      skipRequestCompression: conf.skipRequestCompression,
      authnRequestBinding: conf.authnRequestBinding
    }
    if (!_.isEmpty(conf.audience)) {
      samlConfig.audience = conf.audience
    }
    if (!_.isEmpty(conf.cert)) {
      samlConfig.cert = _.split(conf.cert, '|')
    }
    if (!_.isEmpty(conf.privateCert)) {
      samlConfig.privateCert = conf.privateCert
    }
    if (!_.isEmpty(conf.decryptionPvk)) {
      samlConfig.decryptionPvk = conf.decryptionPvk
    }
39
    passport.use('saml',
Nick's avatar
Nick committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
      new SAMLStrategy(samlConfig, async (profile, cb) => {
        try {
          const userId = _.get(profile, [conf.mappingUID], null) || _.get(profile, 'nameID', null)
          if (!userId) {
            throw new Error('Invalid or Missing Unique ID field!')
          }

          const user = await WIKI.models.users.processProfile({
            profile: {
              id: userId,
              email: _.get(profile, conf.mappingEmail, ''),
              displayName: _.get(profile, conf.mappingDisplayName, '???'),
              picture: _.get(profile, conf.mappingPicture, '')
            },
            providerKey: 'saml'
          })
          cb(null, user)
        } catch (err) {
          cb(err, null)
        }
60 61 62 63
      })
    )
  }
}