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

/* global WIKI */

// ------------------------------------
// Keycloak Account
// ------------------------------------

const KeycloakStrategy = require('@exlinc/keycloak-passport')

module.exports = {
  init (passport, conf) {
13
    passport.use(conf.key,
14
      new KeycloakStrategy({
15 16
        authorizationURL: conf.authorizationURL,
        userInfoURL: conf.userInfoURL,
17
        tokenURL: conf.tokenURL,
18
        host: conf.host,
19 20 21
        realm: conf.realm,
        clientID: conf.clientId,
        clientSecret: conf.clientSecret,
22 23
        callbackURL: conf.callbackURL,
        passReqToCallback: true
24
      }, async (req, accessToken, refreshToken, results, profile, cb) => {
25 26 27 28
        let displayName = profile.username
        if (_.isString(profile.fullName) && profile.fullName.length > 0) {
          displayName = profile.fullName
        }
29 30
        try {
          const user = await WIKI.models.users.processProfile({
31
            providerKey: req.params.strategy,
32 33 34
            profile: {
              id: profile.keycloakId,
              email: profile.email,
35
              name: displayName,
36
              picture: ''
37
            }
38
          })
39
          req.session.keycloak_id_token = results.id_token
40 41 42 43 44 45
          cb(null, user)
        } catch (err) {
          cb(err, null)
        }
      })
    )
46
  },
47
  logout (conf, context) {
48 49 50
    if (!conf.logoutUpstream) {
      return '/'
    } else if (conf.logoutURL && conf.logoutURL.length > 5) {
51 52 53 54 55 56 57 58 59 60 61 62
      const idToken = context.req.session.keycloak_id_token
      const redirURL = encodeURIComponent(WIKI.config.host)
      if (conf.logoutUpstreamRedirectLegacy) {
        // keycloak < 18
        return `${conf.logoutURL}?redirect_uri=${redirURL}`
      } else if (idToken) {
        // keycloak 18+
        return `${conf.logoutURL}?post_logout_redirect_uri=${redirURL}&id_token_hint=${idToken}`
      } else {
        // fall back to no redirect if keycloak_id_token isn't available
        return conf.logoutURL
      }
63 64 65 66
    } else {
      WIKI.logger.warn('Keycloak logout URL is not configured!')
      return '/'
    }
67 68
  }
}