authentication.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const _ = require('lodash')
  2. /* global WIKI */
  3. // ------------------------------------
  4. // OpenID Connect Account
  5. // ------------------------------------
  6. const OpenIDConnectStrategy = require('passport-openidconnect').Strategy
  7. module.exports = {
  8. init (passport, conf) {
  9. passport.use(conf.key,
  10. new OpenIDConnectStrategy({
  11. authorizationURL: conf.authorizationURL,
  12. tokenURL: conf.tokenURL,
  13. clientID: conf.clientId,
  14. clientSecret: conf.clientSecret,
  15. issuer: conf.issuer,
  16. userInfoURL: conf.userInfoURL,
  17. callbackURL: conf.callbackURL,
  18. passReqToCallback: true,
  19. skipUserProfile: conf.skipUserProfile
  20. }, async (req, iss, uiProfile, idProfile, context, idToken, accessToken, refreshToken, params, cb) => {
  21. const profile = Object.assign({}, idProfile, uiProfile)
  22. try {
  23. const user = await WIKI.models.users.processProfile({
  24. providerKey: req.params.strategy,
  25. profile: {
  26. ...profile,
  27. email: _.get(profile, '_json.' + conf.emailClaim),
  28. displayName: _.get(profile, '_json.' + conf.displayNameClaim, '')
  29. }
  30. })
  31. if (conf.mapGroups) {
  32. const groups = _.get(profile, '_json.' + conf.groupsClaim)
  33. if (groups && _.isArray(groups)) {
  34. const currentGroups = (await user.$relatedQuery('groups').select('groups.id')).map(g => g.id)
  35. const expectedGroups = Object.values(WIKI.auth.groups).filter(g => groups.includes(g.name)).map(g => g.id)
  36. for (const groupId of _.difference(expectedGroups, currentGroups)) {
  37. await user.$relatedQuery('groups').relate(groupId)
  38. }
  39. for (const groupId of _.difference(currentGroups, expectedGroups)) {
  40. await user.$relatedQuery('groups').unrelate().where('groupId', groupId)
  41. }
  42. }
  43. }
  44. cb(null, user)
  45. } catch (err) {
  46. cb(err, null)
  47. }
  48. })
  49. )
  50. },
  51. logout (conf) {
  52. if (!conf.logoutURL) {
  53. return '/'
  54. } else {
  55. return conf.logoutURL
  56. }
  57. }
  58. }