authentication.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. }, async (req, iss, uiProfile, idProfile, context, idToken, accessToken, refreshToken, params, cb) => {
  20. const profile = Object.assign({}, idProfile, uiProfile)
  21. try {
  22. const user = await WIKI.models.users.processProfile({
  23. providerKey: req.params.strategy,
  24. profile: {
  25. ...profile,
  26. email: _.get(profile, '_json.' + conf.emailClaim),
  27. displayName: _.get(profile, '_json.' + conf.displayNameClaim, '')
  28. }
  29. })
  30. if (conf.mapGroups) {
  31. const groups = _.get(profile, '_json.' + conf.groupsClaim)
  32. if (groups && _.isArray(groups)) {
  33. const currentGroups = (await user.$relatedQuery('groups').select('groups.id')).map(g => g.id)
  34. const expectedGroups = Object.values(WIKI.auth.groups).filter(g => groups.includes(g.name)).map(g => g.id)
  35. for (const groupId of _.difference(expectedGroups, currentGroups)) {
  36. await user.$relatedQuery('groups').relate(groupId)
  37. }
  38. for (const groupId of _.difference(currentGroups, expectedGroups)) {
  39. await user.$relatedQuery('groups').unrelate().where('groupId', groupId)
  40. }
  41. }
  42. }
  43. cb(null, user)
  44. } catch (err) {
  45. cb(err, null)
  46. }
  47. })
  48. )
  49. },
  50. logout (conf) {
  51. if (!conf.logoutURL) {
  52. return '/'
  53. } else {
  54. return conf.logoutURL
  55. }
  56. }
  57. }