authentication.js 1.9 KB

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